【问题标题】:How to use Microsoft.Extesions.ILogger together with NLog?如何将 Microsoft.Extesions.ILogger 与 NLog 一起使用?
【发布时间】:2021-04-01 13:59:53
【问题描述】:

我有一个系统,我想制作一个自定义日志来为每个用户创建单独的文件夹。现在,我在 NLog.Logger 中像自定义文件目标一样制作它

public static LogFactory ConfigureCustomNLog(string userName)
        {
            var target = new FileTarget();
            target.Name = "fileLog";
            target.FileName = $"${{basedir}}/log" + $"/{userName}/{userName}" + "${shortdate}.log";
            target.Layout =
                "${longdate}|${uppercase:${level}} ${logger}|${message} ${exception:format=ToString,StackTrace}";

            var config = ConfigureNLog("NLog.Config").Configuration;
            config.RemoveTarget("fileLog");
            config.AddTarget(target.Name, target);

            var rule = new LoggingRule(userName, LogLevel.Debug, target);
            config.LoggingRules.Add(rule);

            LogManager.Configuration = config;

            return LogManager.LogFactory;
        }

一切正常,但我想像 Microsoft.Extensions.ILogger 一样使用。如何将 NLog.Logger 导入 ILogger?或者如何为 ILogger 进行自定义配置?

【问题讨论】:

  • Nlog 有一个特殊的 nuget 包,其中包含将 nlog 记录器合并到 MS ILogger 中的方法。我不记得它叫什么,但我知道它存在,因为我在切换到 Serilog 之前使用它,它也有一个类似的包。只需查看他们的 github 页面,肯定有说明
  • 对于控制台应用程序github.com/NLog/NLog/wiki/…,它们也有用于 aspnet 的 wiki 页面。是的,控制台应用程序页面讨论了 netcore2,但它同样适用于更高版本(只需使用更新的包)。老实说,aspnet 说明要好一些,您也可以将它们主要用于控制台应用程序(只是不要使用 nlog.aspnetcore 包)

标签: c# .net nlog ilogger


【解决方案1】:

Microsoft ILogger 通常与依赖注入一起使用。就像这里描述的那样:

https://github.com/NLog/NLog/wiki/Getting-started-with-.NET-Core-2---Console-application

但你也可以手动操作:

class MyClass
{
    private readonly Microsoft.Extensions.Logging.ILogger Logger;
 
    public MyClass(Microsoft.Extensions.Logging.ILoggerFactory loggerFactory)
    {
        Logger = loggerFactory.CreateLogger(GetType().ToString());
        Logger.LogInformation("Hello");
    }
}

var loggerFactory = new NLog.Extensions.Logging.NLogLoggerFactory();
var myClass = new MyClass(loggerFactory);

如果您正在构建 Web 应用程序,那么这可能会有所帮助:https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    • 2011-08-27
    • 2011-04-11
    相关资源
    最近更新 更多