首页 / .NET Core / 正文

Log4net 的 ASP.NET Core 扩展库

3277 发布于: 2020-12-06 读完约需16分钟

给大家安利一款 log4net 的 ASP.NET Core 扩展库,它是基于 log4net 开发的。 简单易用,开源免费,使用ASP.NET Core自身提供的DI容器来实现服务的注册和消费。直接在程序启动时注册到服务中即可完成全部配置,对于小白用户也可快速上手 log4net 日志组件。

Lightweight Logging Extension implementation of log4net.

Install Package

https://www.nuget.org/packages/Log4net.Extension.AspNetCore

Configure

  • Add the AddLog4Net() call into your Configure method of the Startup class.
using Microsoft.Extensions.Logging;

public class Startup
{
    //...

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        //...

        loggerFactory.AddLog4Net(); 

        //...
    }
}
  • Add a log4net.config file with the content:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!-- This section contains the log4net configuration settings -->
  <log4net>
    <appender name="DebugAppender" type="log4net.Appender.ConsoleAppender,log4net">
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
      </layout>
    </appender>
    <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender,log4net">
      <param name="File" value="Logs/" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="&quot;Logs_&quot;yyyyMMdd&quot;_All.txt&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
      </layout>
    </appender>
    <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender,log4net">
      <param name="File" value="Logs/" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="&quot;Logs_&quot;yyyyMMdd&quot;.txt&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="ERROR" />
        <levelMax value="FATAL" />
      </filter>
    </appender>
    <root>
      <level value="ALL" />
      <appender-ref ref="ErrorAppender" />
      <appender-ref ref="InfoAppender" />
    </root>
    <logger name="WebLogger">
      <appender-ref ref="ErrorAppender" />
    </logger>
  </log4net>
</configuration>
  • Add a global ExceptionFilter:
public void ConfigureServices(IServiceCollection services)
{
    //...

    services.AddControllers(options =>
    {
        options.Filters.Add<ExceptionFilter>();
    });

    //...
}
  • appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
  • appsettings.Development.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}
  • Add the log directory as static, so we can view the logs online.
using Microsoft.Extensions.Logging;

public class Startup
{
    //...

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        //...

        loggerFactory.AddLog4Net(); 

        //...

        app.UseFileServer(new FileServerOptions()
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Logs")),
            RequestPath = new PathString("/Log"),
            EnableDirectoryBrowsing = true
        });

        //...
    }
}

Global Exception Filter

public class ExceptionFilter : IExceptionFilter
{
    private readonly ILogger<ExceptionFilter> _logger;
    public ExceptionFilter(ILogger<ExceptionFilter> logger)
    {
        _logger = logger;
    }

    public void OnException(ExceptionContext filterContext)
    {
        var log = new StringBuilder();

        //log the url
        if (filterContext.HttpContext.Request.GetDisplayUrl() != null)
            log.AppendLine(filterContext.HttpContext.Request.GetDisplayUrl());

        log.AppendLine($"\tIP: {filterContext.HttpContext.Connection.RemoteIpAddress}");

        foreach (var key in filterContext.HttpContext.Request.Headers.Keys)
        {
            log.AppendLine($"\t{key}: {filterContext.HttpContext.Request.Headers[key]}");
        }

        var exception = filterContext.Exception;
        log.AppendLine("\tError Message:" + exception.Message);
        if (exception.InnerException != null)
        {
            PrintInnerException(exception.InnerException, log);
        }
        log.AppendLine("\tError HelpLink:" + exception.HelpLink);
        log.AppendLine("\tError StackTrace:" + exception.StackTrace);

        _logger.LogError(log.ToString());
    }

    private void PrintInnerException(Exception ex, StringBuilder log)
    {
        log.AppendLine("\tError InnerMessage:" + ex.Message);
        if (ex.InnerException != null)
        {
            PrintInnerException(ex.InnerException, log);
        }
    }
}

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: ServiceStack.Redis 的 ASP.NET Core 扩展库

下一篇: .NET 5/.NET Core中使用EPPlus导出自定义列标题、忽略列、列排序的静态扩展方法

本文永久链接码友网 » Log4net 的 ASP.NET Core 扩展库

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册