.net core 升级到3.x,变化还是比较多,之前配置的NLog也出了问题,需要重新配置。
安装
直接在NuGet中搜索NLog.Web.AspNetCore
,安装4.9+版本。
创建配置文件
<?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"
throwExceptions="false"
internalLogLevel="Warn"
internalLogFile="Logs\internal-nlog.txt">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<targets>
<!-- 写入文件配置 -->
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="Logs\nlog-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring} ${newline}" />
<!-- another file log, only own logs. Uses some ASP.NET core renderers -->
<target xsi:type="File" name="ownFile-web" fileName="Logs\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} ${newline}" />
</targets>
<rules>
<!--All logs, including from Microsoft-->
<!--minlevel 改为Trace 跟踪全部 Error 只捕获异常-->
<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>
这是官方提供的最简单的配置示例,我稍微修改了输出格式。完整配置参考官方文档。
启用拷贝到bin文件夹
<ItemGroup>
<Content Update="nlog.config" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
在program.cs中配置Nlog
using System;
using NLog.Web;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Hosting;
public static void Main(string[] args)
{
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
logger.Debug("init 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(logging =>
{
// logging.ClearProviders(); // 这个方法会清空所有控制台的输出
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.UseNLog(); // 使用NLog
}
这也是官方示例的例子,我把ClearProviders()
方法注释掉了,因为它会清空所有控制台输出,在测试时看不到任何信息,甚至看不到启动信息,有点尴尬。。。
配置appsettings.json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Trace",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
使用
使用的方式和之前没有什么区别。
using Microsoft.Extensions.Logging;
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
_logger.LogDebug(1, "发生了一个Bug");
}
public IActionResult Index()
{
_logger.LogCritical("Index中发生了一个致命的严重错误,需要马上解决");
return View();
}
}
最后运行
运行后,调用Index后,会在控制台输出(如果您跟我一样注释了ClearProviders()
方法)如下信息:
然后打开Logs文件夹,会看到两个文件,一个all,一个own,在配置项中分别定义了输出内容。
打开文件,会看到如下内容:
文章评论