集成 log4net

本文示例源码: https://github.com/liangshiw/LogDashboard/tree/master/samples/UseLog4net

前言

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

创建NETCore项目

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

安装 log4net 包

Install-Package Microsoft.Extensions.Logging.Log4Net.AspNetCore

添加以下代码到Configure 方法中

loggerFactory.AddLog4Net(new Log4NetProviderOptions
{
    PropertyOverrides =
        new List<NodeInfo>
        {
            new NodeInfo { XPath = "/log4net/appender/file[last()]", Attributes = new Dictionary<string, string> { { "value", $"{AppContext.BaseDirectory}LogFiles/" } } }
        }
});

使用以下配置做为log4net.config,并设置文件属性始终复制到输入目录

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file value="LogFiles/"/>
    <preserveLogFileNameExtension value="true" />
    <datePattern value="yyyy-MM-dd'.log'" />
    <staticLogFileName value="false"/>
    <appendToFile value="true" />
    <maximumFileSize value="100KB" />
    <maxSizeRollBackups value="2" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date || %5level || %logger || %message || %exception ||end %newline" />
    </layout>
  </appender>
  <root>
    <level value="ALL"/>
    <appender-ref ref="RollingFile" />
  </root>
</log4net>

安装LogDashboard

Install-Package LogDashboard

打开Startup.cs

ConfigureServices方法中配置服务

public void ConfigureServices(IServiceCollection services)
{
    services.AddLogDashboard();
}

Configure方法中配置中间件

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseLogDashboard();

    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Hello World!");
    });
}

运行项目导航到/logdashboard

enjoy

Last updated