跟着官网学ASP.NET Core 6.0之日志记录

跟着官网学ASP.NET Core 6.0之日志记录

ASP.NET Core 6.0中,官方提供了内置日志记录提供程序,如:

  • 控制台-提供程序将输出记录到控制台
  • EventLog-提供程序将日志输出发送到 Windows 事件日志

除了内置日志功能外,也有很多第三方日志记录提供程序,这里列举几个比较热门的日志组件:

接下来,我们便学习如何在程序里使用这些组件

Log4Net

安装Log4Net包

创建配置文件

新建一个名为log4net.config的配置文件

加入配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="Console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<!-- Pattern to output the caller's file name and line number -->
<conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
</layout>
</appender>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="example.log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
</layout>
</appender>
<appender name="TraceAppender" type="log4net.Appender.TraceAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ManagedColoredConsoleAppender">
<mapping>
<level value="ERROR" />
<foreColor value="Red" />
</mapping>
<mapping>
<level value="WARN" />
<foreColor value="Yellow" />
</mapping>
<mapping>
<level value="INFO" />
<foreColor value="White" />
</mapping>
<mapping>
<level value="DEBUG" />
<foreColor value="Green" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
</layout>
</appender>
<root>
<level value="TRACE" />
<appender-ref ref="RollingFile" />
<appender-ref ref="TraceAppender" />
<appender-ref ref="ConsoleAppender" />
</root>
</log4net>
使用Log4Net
1
2
builder.Logging.ClearProviders();
builder.Logging.AddLog4Net();

然后在需要记录日志的地方引入,使用ILogger,这里我依然以OrderController为例

1
2
3
4
5
6
7
private readonly ILogger<OrdersController> _logger;

public OrdersController(DemoContext context, ILogger<OrdersController> logger)
{
_context = context;
_logger = logger;
}

当我们访问该接口后,会在控制台打印出相关信息

亦会在运行目录下生成名为example.log的日志文件

NLog

安装NLog

创建配置文件


新建一个名为nlog.config的配置文件,并加入如下配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?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"
throwConfigExceptions="true"
internalLogFile="c:\temp\internal-nlog-AspNetCore6.txt">

<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>

<!-- the targets to write to -->
<targets>
<!-- File Target for all log messages with basic details -->
<target xsi:type="File" name="allfile" fileName="c:\temp\nlog-AspNetCore6-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

<!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
<target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-AspNetCore6-own-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}| body: ${aspnet-request-posted-body}" />

<!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection -->
<target xsi:type="Console" name="lifetimeConsole" layout="${MicrosoftConsoleLayout}" />
</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="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
使用NLog

Program.cs加入如下代码,

1
2
3
builder.Logging.ClearProviders();
builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); //日志级别
builder.Host.UseNLog();

日志是使用方式不变,因为是直接替换的日志的组件,基于接口的日志调用方式不变。

Serilog

安装Serilog


使用Serilog

这里为了演示,我就偷个懒,直接将信息写在代码中,先是配置日志规则

1
2
3
4
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("log-.txt", rollingInterval: RollingInterval.Day, outputTemplate: "{Timestamp:HH:mm} [{Level}] ({ThreadId}) {Message}{NewLine}{Exception}")
.CreateLogger();

然后在使用Serilog

1
builder.Host.UseSerilog(Log.Logger, dispose: true);



一般工作中,用的比较多的可能就是这三种了,听说,Serilog的性能比较好,我没有对比过,所以也不敢乱说,大家可以自己去了解一下。日记记录,就先了解到这里,接下来,我们继续去了解一下ASP.NET Core 6.0模型绑定

跟着官网学ASP.NET Core 6.0之日志记录

https://blogs.52fx.biz/posts/1419082212.html

作者

eyiadmin

发布于

2022-01-30

更新于

2024-05-31

许可协议

评论