我正在为我们的ASP.NET Core 3应用程序设置一些日志记录,使用ILogger(Microsoft.Extensions.Logging)与NLog启用文本文件写入。
问题是,ILogger不会写TRACE和DEBUG级别的消息。无论是到文本文件还是到Visual Studio输出窗口。使用NLog.Logger可以处理所有级别。这个问题在默认的ASP.NET Core 3 Web API应用程序中也存在,该应用程序从官方教程中设置了NLog。以下是我所拥有的相关代码。
Program.cs
public static void Main(string[] args)
{
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
logger.Trace("NLog Trace from Main()");
logger.Debug("NLog Debug from Main()");
logger.Info("NLog Info from Main()");
logger.Warn("NLog Warn from Main()");
logger.Error("NLog Error from Main()");
logger.Fatal("NLog Fatal from Main()");
CreateHostBuilder(args).Build().Run();
}
catch (Exception exception)
{
//NLog: catch setup errors
logger.Error(exception, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging(options =>
{
options.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
}).UseNLog();
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"
autoReload="true"
internalLogLevel="Info"
internalLogFile="c:\temp\internal-nlog.txt">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
<!-- another file log, only own logs. Uses some ASP.NET core renderers -->
<target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- BlackHole without writeTo -->
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Trace",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
天气预报控制器.cs
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
_logger.LogTrace("ILogger LogTrace from WeatherForecastController.");
_logger.LogDebug("ILogger LogDebug from WeatherForecastController.");
_logger.LogInformation("ILogger LogInformation from WeatherForecastController.");
_logger.LogWarning("ILogger LogWarning from WeatherForecastController.");
_logger.LogError("ILogger LogError from WeatherForecastController.");
_logger.LogCritical("ILogger LogCritical from WeatherForecastController.");
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
日志文件输出
2020-05-26 09:48:41.2752||TRACE|NLogTest.Program|NLog Trace from Main() |url: |action:
2020-05-26 09:48:41.3081||DEBUG|NLogTest.Program|NLog Debug from Main() |url: |action:
2020-05-26 09:48:41.3081||INFO|NLogTest.Program|NLog Info from Main() |url: |action:
2020-05-26 09:48:41.3081||WARN|NLogTest.Program|NLog Warn from Main() |url: |action:
2020-05-26 09:48:41.3081||ERROR|NLogTest.Program|NLog Error from Main() |url: |action:
2020-05-26 09:48:41.3081||FATAL|NLogTest.Program|NLog Fatal from Main() |url: |action:
2020-05-26 09:48:41.9009||INFO|NLogTest.Controllers.WeatherForecastController|ILogger LogInformation from WeatherForecastController. |url: https://localhost/weatherforecast|action: Get
2020-05-26 09:48:41.9162||WARN|NLogTest.Controllers.WeatherForecastController|ILogger LogWarning from WeatherForecastController. |url: https://localhost/weatherforecast|action: Get
2020-05-26 09:48:41.9162||ERROR|NLogTest.Controllers.WeatherForecastController|ILogger LogError from WeatherForecastController. |url: https://localhost/weatherforecast|action: Get
2020-05-26 09:48:41.9219||FATAL|NLogTest.Controllers.WeatherForecastController|ILogger LogCritical from WeatherForecastController. |url: https://localhost/weatherforecast|action: Get
现在有人能告诉我为什么ILogger没有记录TRACE和DEBUG消息吗?我已经在Google上搜索了几个小时,并且就我所看到的,一切应该都设置正确了(?)。
谢谢!
appsettings.json
看起来不错。你是否也检查了是否有任何特定于环境的文件,比如appsettings.development.json
?参见https://github.com/NLog/NLog.Web/wiki/Missing-trace%5Cdebug-logs-in-ASP.NET-Core-3%3F - Rolf Kristensen