- 安装包
<ItemGroup>
<PackageReference Include="NLog" Version="4.7.13" />
<PackageReference Include="NLog.Schema" Version="4.7.13" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.14.0" />
</ItemGroup>
- program.cs配置
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host
.CreateDefaultBuilder(args)
.ConfigureLogging((context, logging) =>
{
logging.AddConfiguration(context.Configuration.GetSection("logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
}).UseNLog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.UseServiceProviderFactory(new AutofacServiceProviderFactory()) //自动注入
;
}
- 配置文件配置 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>
<!--这个目标:最终输出文件类型, 位于根目录中得logs文件夹中, 名称以每日得时间一次生成log文件 , layout: 这个选项为生成的格式-->
<target xsi:type="File" name="fileLog"
fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}"
maxArchiveFiles="5"
archiveAboveSize="10240"
archiveEvery="Day"/>
<!--使用可自定义的着色将日志消息写入控制台-->
<target xsi:type="ColoredConsole" name="consoleLog"
layout="[${date:format=HH\:mm\:ss}]:${message} ${exception:format=message}" />
</targets>
<rules>
<!--设定了一个Debug得路由, 最终指向了一个 fileLog 名称得目标 -->
<logger name="*" minlevel="Trace" writeTo="fileLog" />
<logger name="*" minlevel="Trace" writeTo="consoleLog" />
</rules>
</nlog>
``