一、
使用Nuget下载Nlog
或者Nuget下载:NLog.Extensions.Logging
二、配置文件
1、使用配置文件
2、使用自定义配置(使用)
LoggingConfiguration config=new NLog.Config.LoggingConfiguration();
FileTarget t1= new NLog.Targets.FileTarget("file") { FileName = $"logs/{DateTime.Now.ToString("yyyy-MM-dd")}.log",Layout="${longdate}|${level}|${message}" };
config.AddRule(LogLevel.Debug,LogLevel.Error,t1);
LogManager.Configuration = config;
NLog.Logger log = LogManager.GetCurrentClassLogger();
log.Debug("hello world");
使用模板配置:模板链接https://github.com/NLog/NLog.Extensions.Logginghttps://github.com/NLog/NLog.Extensions.Logging设置日志保存大小和保存时长(放置文档多大占用存储空间)
archiveAbovesize="10485760" //日志的大小 maxArchiveFiles="100"//最多保留的日志数量
<target xsi:type="File" name="ownFile-web" fileName="\Logger\${shortdate}.log"
maxArchiveDays="4"
maxArchiveFiles="3"
layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true}|${logger}|${message}" >
</target>
注意:
1、 Getting started with ASP.NET Core 6 · NLog/NLog Wiki · GitHub参考配置教程(配置文件属性 如果较新则复制)
2、是否考虑使用依赖注入(这样使用的话不需要每次都进行实例化了)不使用依赖注入也可使用
配置文件可以试设置成过大自动使用新的文件
完整配置如下:
<?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"
>
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
<target xsi:type="File" name="ownFile-web" fileName="log\Error\${shortdate}.log"
archiveAbovesize="10485760"
maxArchiveFiles="100"
maxArchiveDays="4"
layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true}|${logger}|| ${message}" />
<target xsi:type="File" name="date" fileName="log\Infor\${shortdate}.log"
archiveAbovesize="10485760" maxArchiveFiles="100"
layout="${longdate}|${level:uppercase=true}|${logger}|| ${message}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<!--<logger name="*" minlevel="Trace" writeTo="allfile" />-->
<!--Output hosting lifetime messages to console target for faster startup detection -->
<!--<logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole, ownFile-web" final="true" />
--><!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) --><!--
<logger name="Microsoft.*" maxlevel="Info" final="true" />
<logger name="System.Net.Http.*" maxlevel="Info" final="true" />-->
<logger name="*" level="Debug" writeTo="ownFile-web" />
<logger name="*" level="Info" writeTo="date" />
</rules>
</nlog>