集成 log4net

前言

log4net是Net平台下老牌日志组件,logdashboard完全适配log4net,但由于log4net不支持在Net Core将日志写到数据库,所以logdashboard并不推荐使用log4net做为最佳实践

创建NETCore项目

如同快速入门一样,我们需要创建一个NETCore项目,不在赘述此过程

安装 log4net 包

1
Install-Package Microsoft.Extensions.Logging.Log4Net.AspNetCore
Copied!
添加以下代码到Configure 方法中
1
loggerFactory.AddLog4Net(new Log4NetProviderOptions
2
{
3
PropertyOverrides =
4
new List<NodeInfo>
5
{
6
new NodeInfo { XPath = "/log4net/appender/file[last()]", Attributes = new Dictionary<string, string> { { "value", quot;{AppContext.BaseDirectory}LogFiles/" } } }
7
}
8
});
Copied!
使用以下配置做为log4net.config,并设置文件属性始终复制到输入目录
1
<?xml version="1.0" encoding="utf-8" ?>
2
<log4net>
3
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
4
<file value="LogFiles/"/>
5
<preserveLogFileNameExtension value="true" />
6
<datePattern value="yyyy-MM-dd'.log'" />
7
<staticLogFileName value="false"/>
8
<appendToFile value="true" />
9
<maximumFileSize value="100KB" />
10
<maxSizeRollBackups value="2" />
11
<layout type="log4net.Layout.PatternLayout">
12
<conversionPattern value="%date || %5level || %logger || %message || %exception ||end %newline" />
13
</layout>
14
</appender>
15
<root>
16
<level value="ALL"/>
17
<appender-ref ref="RollingFile" />
18
</root>
19
</log4net>
Copied!

安装LogDashboard

1
Install-Package LogDashboard
Copied!
打开Startup.cs
ConfigureServices方法中配置服务
1
public void ConfigureServices(IServiceCollection services)
2
{
3
services.AddLogDashboard();
4
}
Copied!
Configure方法中配置中间件
1
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
2
{
3
if (env.IsDevelopment())
4
{
5
app.UseDeveloperExceptionPage();
6
}
7
8
app.UseLogDashboard();
9
10
app.Run(async (context) =>
11
{
12
await context.Response.WriteAsync("Hello World!");
13
});
14
}
Copied!
运行项目导航到/logdashboard
enjoy