Log4Net从Mvc转到.Net Core

原项目用的Log4Net,不过版本比较旧,在Core里新版也进行了支持,本文用的是现在最新版本2.0.8

1、LogHelper帮助类放另一个类库中 Log/LogHelper.cs

2、单独建的配置文件放在主项目下,LogConfig/Log4Net.config

具体位置如下图:

Log4Net从Mvc转到.Net Core_第1张图片


LogHelper.cs内容
升级版本后本来的LogManager.GetLogger()方法要指定Repository 看文章都是要
CreateRepository一个.
  private static readonly ILoggerRepository Repository = LogManager.CreateRepository(Assembly.GetEntryAssembly(), typeof(Hierarchy))
不过我这样写就是不行,没有报错日志也不会写入.后面研究半天用GetRepository解决.
  private static readonly ILoggerRepository Repository = LogManager.GetRepository(Assembly.GetCallingAssembly());
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Concurrent;
using System.IO;
using System.Reflection;
using log4net;
using log4net.Config;
using log4net.Repository;
using log4net.Repository.Hierarchy;

//指定log4net使用的config文件来读取配置信息
[assembly: XmlConfigurator(ConfigFile = @"LogConfig\Log4Net.config", Watch = true)]
namespace C.Until
{
    /// 
    /// 日志帮助类
    /// 
    public class LogHelper
    {
        #region 旧版本
        //private static readonly ILog Loginfo = LogManager.GetLogger("loginfo");
        //private static readonly ILog LogError = LogManager.GetLogger("logerror");
        #endregion


        private static readonly ILoggerRepository Repository = LogManager.GetRepository(Assembly.GetCallingAssembly());
        private static readonly ILog Loginfo = LogManager.GetLogger(Repository.Name, "loginfo");
        private static readonly ILog LogError = LogManager.GetLogger(Repository.Name, "logerror");

        public static void Error(string errorMsg, Exception ex = null)
        {
            if (ex != null)
            {
                LogError.Error(errorMsg, ex);
            }
            else
            {
                LogError.Error(errorMsg);
            }
        }

        public static void Info(string msg)
        {
            Loginfo.Info(msg);
        }
    }
}

Log4Net.config

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

  
    
    
"log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> "Log4Net_INFO" type="log4net.Appender.RollingFileAppender"> "Log\\LogInfo\\" /> "utf-8" /> "true"/> "Date"/> ""log"yyyyMM".log"" /> "false"/> "log4net.Appender.FileAppender+MinimalLock" /> "log4net.Layout.PatternLayout"> "记录时间:%date %n错误描述:%message%newline %n" /> "Log4Net_ERROR" type="log4net.Appender.RollingFileAppender"> "Log\\LogError\\" /> "utf-8" /> "true"/> "Date"/> ""log"yyyyMM".log"" /> "false"/> "log4net.Appender.FileAppender+MinimalLock" /> "log4net.Layout.PatternLayout"> "记录时间:%date %n错误描述:%message%newline %n" /> "logerror"> "ERROR" /> ref ref="Log4Net_ERROR" /> "loginfo"> "INFO" /> ref ref="Log4Net_INFO" />

这里因为不同消息放在不同文件 分类处理用的“ogger name="logerror" 此种属性.

ps:在LogHelper.cs文件中用[assembly: XmlConfigurator(ConfigFile = @"LogConfig\Log4Net.config", Watch = true)]来读取配置文件,也可以在Startup.cs中注册文件路径.不过为了独立性 方便移植到别的项目中就没用此方法.

 

你可能感兴趣的:(Log4Net从Mvc转到.Net Core)