首页 > 解决方案 > 使用 .Net Core 2.1 实现 Castle.Core.Logging.ILoggerFactory 接口

问题描述

我正在尝试在我的控制器操作中通过 IoC 使用 NLog 创建日志条目通过遵循https://davidsiew.wordpress.com/2013/08/07/castle-windsor-nlog-integration/教程,我发现我需要在 MyWindsorInstaller 类中更改一行。本教程的来源:https ://github.com/DavidSSL/CastleWindsorWithNlog?source=c

而不是这个:

container.AddFacility<LoggingFacility>(f => f.LogUsing(LoggerImplementation.NLog).WithConfig("NLog.config"));

我需要使用这个:

container.AddFacility<LoggingFacility>(f => f.LogUsing<NLogLoggerFactory> ().WithConfig("NLog.config"));

这里 NLogLoggerFactory 是实现 Castle.Core.Logging 的类。ILoggerFactory接口,现在我需要添加实现。现在它看起来像这样:

using Castle.Core.Logging;

public class NLogLoggerFactory : ILoggerFactory
{
    private ILogger logger = NullLogger.Instance;

    public ILogger Create(Type type)
    {
        throw new NotImplementedException();
    }

    public ILogger Create(string name)
    {
        throw new NotImplementedException();
    }

    public ILogger Create(Type type, LoggerLevel level)
    {
        throw new NotImplementedException();
    }

    public ILogger Create(string name, LoggerLevel level)
    {
        throw new NotImplementedException();
    }

    // ...
}

但是为什么它有 4 种不同的 Create() 方法呢?当然那是因为接口有它。但我不确定接下来会发生什么。如果我尝试初始化 Nlog 记录器,它不会允许我,因为 NLog 不是必需的返回类型。所以我想知道也许有人有任何提示,或者这个实现的例子?

标签: .netasp.net-corecastle-windsornlog

解决方案


您不需要创建自己的NLogLoggerFactory. 开箱即用已经提供了一个。

只需NLogFactoryCastle.Services.Logging.NLogIntegration命名空间使用。


推荐阅读