Nlog 实现了 Microsoft.Extensions.Logging.ILogger。
首先Nuget下载添加引用:NLog.Extensions.Logging
在添加NLog的配置文件“NLog.Config” 到项目,内容如下:
<?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <targets> <target name="logfile" xsi:type="File" fileName="Log/log.txt" /> <target name="console" xsi:type="Console" /> </targets> <rules> <logger name="*" minlevel="Info" writeTo="logfile" /> <logger name="*" minlevel="Info" writeTo="console" /> </rules> </nlog>
在:Program 类(我这个是Console程序)修改:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args).ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddNLog();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<DataService>();
});
在用的地方注入Microsoft.Extensions.Logging.ILogger:
private Microsoft.Extensions.Logging.ILogger<DataService> _logger; public DataService(ILogger<DataService> logger) { _logger = logger; } protected void Test() { _logger.LogError("test.........");
最后会在 Log/log.txt 记录日志输出信息。
另外可以定义为 NLog.ILogger _logger;
可惜的是NLog没有NLog.ILogger<T>这种形式!!!!
也不能直接注入NLog.ILogger,会报 ‘Unable to resolve service for type ‘NLog.ILogger‘ while attempting to activate 。
可以这样:
private readonly Logger _logger; public DataService() { _logger = LogManager.GetCurrentClassLogger(); }