一佳一

记录像1+1一样简洁的代码

导航

asp.net core 3.1 使用log4net

Posted on 2020-05-29 11:43  一佳一  阅读(1041)  评论(1编辑  收藏  举报

1.引用Log4net到项目中,搜NuGet包  Log4net 现在最新是 Version 2.0.8

2.在项目中添加log4net.config文件,右键改文件属性-》复制到输出目录选择-》始终复制

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="DebugAppender" type="log4net.Appender.DebugAppender" >
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>
  <!--指定日记记录方式,以滚动文件的方式(文件记录)-->
  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <!--日志路径-->
    <file value="Log/" />
    <!--是否是向文件中追加日志-->
    <appendToFile value="true" />
    <!--log保留天数-->
    <param name= "MaxSizeRollBackups" value= "10"/>
    <!--每个文件最大1M-->
    <param name="maximumFileSize" value="1MB" />
    <!--日志根据日期滚动-->
    <param name="RollingStyle" value="Date" />
    <!--日志文件名格式为:logs_20080831.log-->
    <param name="DatePattern" value="&quot;logs_&quot;yyyyMMdd&quot;.log&quot;" />
    <!--日志文件名是否是固定不变的-->
    <param name="StaticLogFileName" value="false" />
    <!--布局-->
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
    </layout>
  </appender>
  <root>
    <level value="ALL"/>
    <appender-ref ref="DebugAppender" />
    <appender-ref ref="RollingFile" />
  </root>
</log4net>

3.编写Log4netHelper

using log4net;
using log4net.Repository;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;

namespace NF.Common.Utility
{
    /// <summary>
    /// 日志等级
    /// </summary>
    public enum LogLevel
    {
        Error,
        Debug,
        Warning,
        Info
    }
    /// <summary>
    /// 单例模式初始化
    /// </summary>
    public class Singleton
    {
        private ILog Log;
        private static Singleton instance;
        private Singleton() { }
        public static Singleton getInstance()
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
        /// <summary>
        /// 获取日志初始化器
        /// </summary>
        /// <param name="type">类名 方法名</param>
        /// <returns></returns>
        public ILog Init(string type)
        {
            Log = LogManager.GetLogger(Log4netHelper.Repository.Name, type);
            return Log;
        }
    }
    /// <summary>
    /// 日志操作类
    /// </summary>
    public class Log4netHelper
    {
        /// <summary>
        /// log4net 仓储
        /// </summary>
        public static ILoggerRepository Repository { get; set; }
        /// <summary>
        /// 输出Erro日志
        /// </summary>
        /// <param name="message">日志内容</param>
        public static void Error(string message)
        {
            StackTrace trace = new StackTrace();
            //获取是哪个类来调用的  
            var className = trace.GetFrame(1).GetMethod().DeclaringType;
            //获取方法名称
            MethodBase method = trace.GetFrame(1).GetMethod();
            var type = "类名:" + className.Namespace + "\r\n\r\t\r\r方法名:" + method.Name;
            WriteLog(LogLevel.Error, message, type);
        }
        /// <summary>
        /// 输出Warning日志
        /// </summary>
        /// <param name="message">日志内容</param>
        public static void Warning(string message)
        {
            StackTrace trace = new StackTrace();
            //获取是哪个类来调用的  
            var className = trace.GetFrame(1).GetMethod().DeclaringType;
            //获取方法名称
            MethodBase method = trace.GetFrame(1).GetMethod();
            var type = "类名:" + className.Namespace + "\r\n\r\t\r\r方法名:" + method.Name;
            //记录日志
            WriteLog(LogLevel.Warning, message, type);
        }
        /// <summary>
        /// 输出Info日志
        /// </summary>
        /// <param name="message">日志内容</param>
        public static void Info(string message)
        {
            StackTrace trace = new StackTrace();
            //获取是哪个类来调用的  
            var className = trace.GetFrame(1).GetMethod().DeclaringType;
            //获取方法名称
            MethodBase method = trace.GetFrame(1).GetMethod();
            var type = "类名:" + className.Namespace + "\r\n\r\t\r\r方法名:" + method.Name;
            //记录日志
            WriteLog(LogLevel.Info, message, type);
        }
        /// <summary>
        /// 输出Debug日志
        /// </summary>
        /// <param name="message">日志内容</param>
        public static void Debug(string message)
        {
            StackTrace trace = new StackTrace();
            //获取是哪个类来调用的  
            var className = trace.GetFrame(1).GetMethod().DeclaringType;
            //获取方法名称
            MethodBase method = trace.GetFrame(1).GetMethod();
            var type = "类名:" + className.Namespace + "\r\n\r\t\r\r方法名:" + method.Name;
            //记录日志
            WriteLog(LogLevel.Debug, message, type);
        }
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="logLevel">日志等级</param>
        /// <param name="message">日志信息</param>
        /// <param name="type">类名 方法名</param>
        private static void WriteLog(LogLevel logLevel, string message, string type)
        {
            ILog Log = Singleton.getInstance().Init(type);
            switch (logLevel)
            {
                case LogLevel.Debug:
                    Log.Debug(message);
                    break;
                case LogLevel.Error:
                    Log.Error(message);
                    break;
                case LogLevel.Info:
                    Log.Info(message);
                    break;
                case LogLevel.Warning:
                    Log.Warn(message);
                    break;
            }

        }
    }
}

4、修改Startup 在ConfigureServices(IServiceCollection services)方法里加入如下代码:

Log4netHelper.Repository = LogManager.CreateRepository("NETCoreRepository");
            XmlConfigurator.Configure(Log4netHelper.Repository, new FileInfo(Environment.CurrentDirectory + "/Config/log4net.config"));