.netcore项目中使用log4net

log4net配置文件

        引入log4net包,创建一个config目录,专门用来放配置文件,添加log4net.config文件。

.netcore项目中使用log4net_第1张图片

        编写配置文件。

"1.0" encoding="utf-8"?>

  
  
    
    "errLog">
      "ALL" />
      ref ref="ErrorAppender" />
    
    
    "ErrorAppender" type="log4net.Appender.RollingFileAppender">
      
      "File" value="Log\\LogError\\" />
      
      "AppendToFile" value="true" />
      
      "MaxSizeRollBackups" value="2" />
      
      "MaxFileSize" value="10485760" />
      
      
      
      "StaticLogFileName" value="false" />
      
      "DatePattern" value="yyyy-MM-dd".htm"" />
      
      "RollingStyle" value="Composite" />
      
      "log4net.Layout.PatternLayout">
        "ConversionPattern" value="<HR COLOR=red>%n【异常时间】:%d [%t] <BR>%n【异常级别】:%-5p <BR>%n%m <BR>%n <HR Size=1>"  />
      
    

    
    "infoLog">
      "ALL" />
      ref ref="InfoAppender" />
    
    
    "InfoAppender" type="log4net.Appender.RollingFileAppender">
      "File" value="Log\\LogInfo\\" />
      "AppendToFile" value="true" />
      "MaxSizeRollBackups" value="2" />
      "MaximumFileSize" value="1024KB" />
      "StaticLogFileName" value="false" />
      "DatePattern" value="yyyy-MM-dd".htm"" />
      "RollingStyle" value="Composite" />
      "log4net.Layout.PatternLayout">
        "ConversionPattern" value="<HR COLOR=blue>%n【日志时间】:%d [%t] <BR>%n【日志级别】:%-5p <BR>%n%m <BR>%n <HR Size=1>"  />
      
    
    
  
  

 

 

日志帮助类

        首先创建一个仓储类

public class Log4NetRepository
{
    public static ILoggerRepository loggerRepository { get; set; }
}
    /// 
    /// log4net帮助类
    /// AdoNetAppender仅支持到.net framework4.5,不支持在.net core项目中持久化日志到数据库
    /// 
    public class LogHelper
    {
        // 异常 // 注意:logger name不要写错
        private static readonly ILog logerror = LogManager.GetLogger(Log4NetRepository.loggerRepository.Name, "errLog");
        // 记录
        private static readonly ILog loginfo = LogManager.GetLogger(Log4NetRepository.loggerRepository.Name, "infoLog");

        public static void Error(string throwMsg, Exception ex)
        {
            string errorMsg = string.Format("【异常描述】:{0} 
【异常类型】:{1}
【异常信息】:{2}
【堆栈调用】:{3}
", new object[] { throwMsg, ex.GetType().Name, ex.Message, ex.StackTrace }); errorMsg = errorMsg.Replace("\r\n", "
"); logerror.Error(errorMsg); } public static void Info(string message) { loginfo.Info(string.Format("【日志信息】:{0}",message)); } }

        startup引用log4netlog4net.Configlog4net.Repository。在startup的构造函数中这么配置:

public static ILoggerRepository repository { get; set; }

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
    // log4net 仓储
    repository = LogManager.CreateRepository("CoreLogRepository");
    XmlConfigurator.Configure(repository, new FileInfo("config/log4net.config"));
    Log4NetRepository.loggerRepository = repository;
}

        之前写好了全局异常捕获,现在可以加上这么一句。

public class ApiExceptionFilter:ExceptionFilterAttribute
    {
        private IHostingEnvironment _env;
        public ApiExceptionFilter(IHostingEnvironment env)
        {
            _env = env;
        }

        public override void OnException(ExceptionContext context)
        {
            if (context.ExceptionHandled)
            {
                return;
            }
            LogHelper.Error(exMsg, context.Exception); // 日志记录
            var exMsg = context.Exception.Message;
            ApiResp resp = new ApiResp(ApiRespCode.E999999,exMsg);
            // 开发环境显示异常信息
            if(_env.IsDevelopment())
            {
                resp.Message = exMsg;
            }
            context.Result = new JsonResult(resp);
            context.ExceptionHandled = true;
        }
    }

  当发生异常时,会自动在项目目录创建Log\LogError\目录,并写入日志文件。

 

你可能感兴趣的:(.netcore项目中使用log4net)