一、为什么分类
因为如果不进行分类所有级别的日志都放在一起非常的杂乱。 也不便于查询错误信息,在项目发布初还没稳定需要所有信息,之后稳定只需要警告级别以上的信息时就可以启到过滤效果。 只有Error级别
二、实例展示
创建一个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"
throwConfigExceptions="true"
internalLogLevel="info"
internalLogFile="internal-nlog-AspNetCore3.txt">
<!-- 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="sysServicesFile" archiveAboveSize="10000" maxArchiveFiles ="3" fileName="logs/sysService-${shortdate}.log"
layout="${date}|${level:uppercase = true}|${logger}|${message} ${exception:format=ToString}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="_01_Logging.*" minlevel="Trace" writeTo="sysServicesFile" final="true" /> <!-- BlackHole -->
</rules>
</nlog>
NLog的提供的服务日志类,要自己创建 Program
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System;
namespace _01_Logging
{
class Program
{
static void Main(string[] args)
{
ServiceCollection services = new ServiceCollection();
services.AddLogging(
logBuilder=>
{
logBuilder.AddConsole();
logBuilder.AddNLog();
logBuilder.SetMinimumLevel(LogLevel.Trace);
}
);
services.AddScoped<SystemService>();
using (var sp = services.BuildServiceProvider())
{
var test2 = sp.GetRequiredService<SystemService>();
for (int i = 1; i <= 1000; i++)
{
test2.Logging();
}
}
}
}
}
源码地址
https://github.com/1768894221/CSharp
三、NLog其他
1.NLog部分功能与.Net的Logging功能重复,比如分类、分级,各种Provider 2.为了避免冲突如果使用NLog,不要在使用微软的分级(具体用法见微软官方文档)
3.其他输出扩展文档,可以向redis,邮件等多个地方输出 https://nlog-project.org/config/
|