C#-Log4net 封装log类并自定义log存放路径

  • Post author:
  • Post category:其他


引用dll :  log4net.dll

接口类:ILogger.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HCCD.Base.Comm.NewLogger
{
    /// <summary>
    /// 日志接口
    /// </summary>
    public interface ILogger
    {
        /// <summary>
        /// 调试日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        void Debug(string msg);

        /// <summary>
        /// 调试日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        /// <param name="ex">输出异常</param>
        void Debug(string msg, Exception ex);

        /// <summary>
        /// 信息日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        void Info(string msg);

        /// <summary>
        /// 信息日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        /// <param name="ex">输出异常</param>
        void Info(string msg, Exception ex);

        /// <summary>
        /// 警告日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        void Warn(string msg);

        /// <summary>
        /// 警告日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        /// <param name="ex">输出异常</param>
        void Warn(string msg, Exception ex);

        /// <summary>
        /// 错误日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        void Error(string msg);

        /// <summary>
        /// 错误日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        /// <param name="ex">输出异常</param>
        void Error(string msg, Exception ex);

        /// <summary>
        /// 致命日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        void Fatal(string msg);

        /// <summary>
        /// 致命日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        /// <param name="ex">输出异常</param>
        void Fatal(string msg, Exception ex);
    }
}

接口实现类:LogHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using log4net.Appender;
using System.IO;
using log4net.Config;

namespace HCCD.Base.Comm.NewLogger
{
    /*
     * Author: Long
     * Date: 2019-09
     * Detail: Log4net日志类
     */

    /// <summary>
    /// Log4net日志类
    /// </summary>
    public class LogHelper : ILogger
    {
        private Dictionary<string, ILog> LogDic = new Dictionary<string, ILog>();
        private object _islock = new object();
        private string fileName = string.Empty;

        /// <summary>
        /// 日志调用初始化
        /// </summary>
        /// <param name="fileSavePath">日志文件保存路径[若路径为空,则默认程序根目录Logger文件夹;]</param>
        /// <param name="fileName">日志文件名[若文件名为空,则默认文件名:Default]</param>
        public LogHelper(string fileSavePath, string fileName,string logSuffix = ".log")
        {
            try
            {
                Init();
                if (string.IsNullOrEmpty(fileSavePath))
                    fileSavePath = "Logger";
                if (string.IsNullOrEmpty(fileName))
                    fileName = "Default";

                this.fileName = fileName;
                var repository = LogManager.GetRepository();
                var appenders = repository.GetAppenders();

                if (appenders.Length == 0) return;
                var targetApder = appenders.First(p => p.Name == "FileInfoAppender") as RollingFileAppender;
                targetApder.File = Path.Combine(fileSavePath, this.fileName + logSuffix);
                targetApder.ActivateOptions();
            }
            catch (Exception ex) { }
        }

        /// <summary>
        /// 缓存日志对象
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private ILog GetLog(string name)
        {
            try
            {
                if (LogDic == null)
                {
                    LogDic = new Dictionary<string, ILog>();
                }
                lock (_islock)
                {
                    if (!LogDic.ContainsKey(name))
                    {
                        LogDic.Add(name, LogManager.GetLogger(name));
                    }
                }
                return LogDic[name];
            }
            catch
            {
                return LogManager.GetLogger("Default");
            }
        }

        /// <summary>
        /// 日志记录初始化
        /// </summary>
        private void Init()
        {
            var file = new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log4net.config"));
            XmlConfigurator.Configure(file);
        }

        /// <summary>
        /// 调试日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        public void Debug(string msg)
        {
            var log = GetLog(this.fileName);
            if (log == null)
            {
                return;
            }
            log.Debug(msg);
        }

        /// <summary>
        /// 调试日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        /// <param name="ex">输出异常</param>
        public void Debug(string msg, Exception ex)
        {
            var log = GetLog(this.fileName);
            if (log == null)
            {
                return;
            }
            log.Debug(msg, ex);
        }


        /// <summary>
        /// 信息日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        public void Info(string msg)
        {
            var log = GetLog(this.fileName);
            if (log == null)
            {
                return;
            }
            log.Info(msg);
        }

        /// <summary>
        /// 信息日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        /// <param name="ex">输出异常</param>
        public void Info(string msg, Exception ex)
        {
            var log = GetLog(this.fileName);
            if (log == null)
            {
                return;
            }
            log.Info(msg, ex);
        }

        /// <summary>
        /// 警告日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        public void Warn(string msg)
        {
            var log = GetLog(this.fileName);
            if (log == null)
            {
                return;
            }
            log.Warn(msg);
        }

        /// <summary>
        /// 警告日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        /// <param name="ex">输出异常</param>
        public void Warn(string msg, Exception ex)
        {
            var log = GetLog(this.fileName);
            if (log == null)
            {
                return;
            }
            log.Warn(msg, ex);
        }

        /// <summary>
        /// 错误日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        public void Error(string msg)
        {
            var log = GetLog(this.fileName);
            if (log == null)
            {
                return;
            }
            log.Error(msg);
        }

        /// <summary>
        /// 错误日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        /// <param name="ex">输出异常</param>
        public void Error(string msg, Exception ex)
        {
            var log = GetLog(this.fileName);
            if (log == null)
            {
                return;
            }
            log.Error(msg, ex);
        }

        /// <summary>
        /// 致命日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        public void Fatal(string msg)
        {
            var log = GetLog(this.fileName);
            if (log == null)
            {
                return;
            }
            log.Fatal(msg);
        }

        /// <summary>
        /// 致命日志输出
        /// </summary>
        /// <param name="msg">输出内容</param>
        /// <param name="ex">输出异常</param>
        public void Fatal(string msg, Exception ex)
        {
            var log = GetLog(this.fileName);
            if (log == null)
            {
                return;
            }
            log.Fatal(msg, ex);
        }
    }
}

配置类:Log4net.config

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>
  <!--站点日志配置部分-->
  <log4net>
    <!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
    <!-- Set root logger level to ERROR and its appenders -->
    <root>
      <!--控制级别,由低到高: ALL|DEBUG|INFO|WARN|ERROR|FATAL|OFF-->
      <!--比如定义级别为INFO,则INFO级别向下的级别,比如DEBUG日志将不会被记录-->
      <!--如果没有定义LEVEL的值,则缺省为DEBUG-->
      <level value="ALL"/>
      <appender-ref ref="FileInfoAppender"/>
    </root>
    <appender name="FileInfoAppender" type="log4net.Appender.RollingFileAppender">
      <!--多线程时采用最小锁定-->
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
      <file/>
      <param name="AppendToFile" value="true"/>
      <param name="RollingStyle" value="Date"/>
      <datePattern value="&quot;.&quot;yyyy-MM-dd&quot;.log&quot;"/>
      <!--固定文件名-->
      <param name="StaticLogFileName" value="true"/>
      <encoding value="utf-8"/>
      <!--日志输出格式-->
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%p] %m%n"/>
      </layout>
    </appender>
  </log4net>
</configuration>

调用方式

引用:log4net.dll

HCC.Base.Comm.NewLogger.dll

实现:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HCC.Base.Comm.NewLogger;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            LogHelper log = new LogHelper(@"D:\Logger", "stydy");

            log.Info("广东省个大三噶的首付打好分单发核辐射的");
            log.Info("广东省个大三噶的首付打好分单发核辐射的", new Exception("请检查系统异常!这个问题是相当的严重。"));

            log.Fatal("gdsgdsgdsgdsgdsgds");
            log.Fatal("gdsgdsgdsgdsgdsgds", new Exception("请检查系统异常!这个问题是相当的严重。"));

            log.Warn("广东省个大三噶电视柜电视柜");
            log.Warn("gdsgdsgdsgdsgdsgds", new Exception("请检查系统异常!这个问题是相当的严重。"));

            log.Debug("cbvcbvfgsfgdsgdsgdsgdsgdsgds");
            log.Debug("gdsgdsgdsgdsgdsgds", new Exception("请检查系统异常!这个问题是相当的严重。"));

            log.Error("系统异常");
            log.Error("系统异常",new Exception("请检查系统异常!这个问题是相当的严重。"));
        }
    }
}



版权声明:本文为wanlong360599336原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。