把Log4net封装成单独的类库,为其他项目使用

项目搭建

在日常开发中,经常需要使用日志,而且我们公司的在C#开发的基本上都是使用的log4net,每次都需要重新添加log4net的引用和配置。

所以想使用一个单独的类库,供其他项目之间引用,就可以完成日志功能,具体的日志,则由单独的类库来维护,先写一个简单的版本,后续继续优化,以及方便调用。

创建类库

首先创建一个类库LogsLibrary,框架结构如下:

 

添加引用

 在引用中添加对log4net.dll文件的引用,如下图

 

 

设置log配置文件及属性

配置Log4net.config文件,每个项目可能会有不同,大家自行修改。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <!-- This section contains the log4net configuration settings -->
  <log4net>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" />
    </appender>

    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="log-file.log" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread]111 %-5level %logger [%property{NDC}] - %newline%message%newline" />
      </layout>
    </appender>

    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="Logs/" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <staticLogFileName value="false" />
      <datePattern value="yyyyMMdd'.log'" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%newline%date [%thread]222 %-5level %logger [%property{NDC}] -- %newline%message%newline" />
      </layout>
    </appender>

    <!-- Setup the root category, add the appenders and set the default level -->
    <root>
      <level value="ALL" />
      <appender-ref ref="ConsoleAppender" />
    </root>


    <logger name="LoggerSystem">
      <level value="ALL" />
      <appender-ref ref="RollingLogFileAppender" />
    </logger>

  </log4net>
</configuration>

 

右键Log4net.config文件,在属性窗口选择“始终复制”,如下图

 

 初始化Log4net对象

编辑LogHelp.cs文件的代码也比较简单,如下:

    public class LogHelp
    {
        public static log4net.ILog SystemLog;
        //public static log4net.ILog ConsoleLog;

        public static bool InitLog()
        {
            try
            {
                SystemLog = log4net.LogManager.GetLogger("LoggerSystem");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("加载日志配置文件时,发生一次" + ex.ToString());
                return false;
            }
        }
    }

 

另外,需要在AssemblyInfo.cs文件最后,增加一行,如下

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4net.config", ConfigFileExtension = "config", Watch = true)]

 

调用类库方法写日志

新建一个应用程序,并添加Log4net和LogsLibrary类库的引用,项目结构如下图:

 

 调用代码如下:

namespace ConsoleApp1
{
    using LogsLibrary;


    class Program
    {
        static void Main(string[] args)
        {
            LogHelp.InitLog();
            LogHelp.SystemLog.Info("-----Test.Info--");

            Console.ReadKey();
        }
    }
}

 

后续使用的时候,将根据使用进行优化。

 

优化1

在上面的调用程序中必须引用类库,否则无法运行,我又增加了一个中间类,可以不引用Log4net也可以调用,如下:

namespace LogsLibrary
{
    /// <summary>
    /// 日志类
    /// </summary>
    public abstract class Log4netHelper
    {
        //系统框架日志

        private static ILog Logger => LogManager.GetLogger("LoggerSystem");


        //框架内部方法

        #region 调试信息
        /// <summary>
        /// 调试信息
        /// </summary>
        /// <param name="message">描述信息</param>
        /// <param name="exception">异常信息</param>
        public static void Debug(object message, Exception exception = null)
        {
            Logger.Debug(message, exception);
        }
        public static void DebugFormat(string format, params object[] args)
        {
            Logger.DebugFormat(format, args);
        }
        public static void DebugFormat(Exception exception, string format, params object[] args)
        {
            Logger.DebugFormat(format, args, exception);
        }
        public static void DebugFormat(IFormatProvider formatProvider, string format, params object[] args)
        {
            Logger.DebugFormat(formatProvider, format, args);
        }
        public static void DebugFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
        {
            Logger.DebugFormat(formatProvider, format, args, exception);
        }
        #endregion

        #region 一般信息
        /// <summary>
        /// 一般信息
        /// </summary>
        /// <param name="message">描述信息</param>
        /// <param name="exception">异常信息</param>
        public static void Info(object message, Exception exception = null)
        {
            Logger.Info(message, exception);
        }
        public static void InfoFormat(string format, params object[] args)
        {
            Logger.InfoFormat(format, args);
        }
        public static void InfoFormat(Exception exception, string format, params object[] args)
        {
            Logger.InfoFormat(format, args, exception);
        }
        public static void InfoFormat(IFormatProvider formatProvider, string format, params object[] args)
        {
            Logger.InfoFormat(formatProvider, format, args);
        }
        public static void InfoFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
        {
            Logger.InfoFormat(formatProvider, format, args, exception);
        }
        #endregion

        #region 警告
        /// <summary>
        /// 警告
        /// </summary>
        /// <param name="message">描述信息</param>
        /// <param name="exception">异常信息</param>
        public static void Warn(object message, Exception exception = null)
        {
            Logger.Warn(message, exception);
        }
        public static void WarnFormat(string format, params object[] args)
        {
            Logger.WarnFormat(format, args);
        }
        public static void WarnFormat(Exception exception, string format, params object[] args)
        {
            Logger.WarnFormat(format, args, exception);
        }
        public static void WarnFormat(IFormatProvider formatProvider, string format, params object[] args)
        {
            Logger.WarnFormat(formatProvider, format, args);
        }
        public static void WarnFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
        {
            Logger.WarnFormat(formatProvider, format, args, exception);
        }
        #endregion

        #region 一般错误
        /// <summary>
        /// 一般错误
        /// </summary>
        /// <param name="message">描述信息</param>
        /// <param name="exception">异常信息</param>
        public static void Error(object message, Exception exception = null)
        {
            Logger.Error(message, exception);
        }
        public static void ErrorFormat(string format, params object[] args)
        {
            Logger.ErrorFormat(format, args);
        }
        public static void ErrorFormat(Exception exception, string format, params object[] args)
        {
            Logger.ErrorFormat(format, args, exception);
        }
        public static void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args)
        {
            Logger.ErrorFormat(formatProvider, format, args);
        }
        public static void ErrorFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
        {
            Logger.ErrorFormat(formatProvider, format, args, exception);
        }
        #endregion

        #region 致命错误
        /// <summary>
        /// 致命错误
        /// </summary>
        /// <param name="message">描述信息</param>
        /// <param name="exception">异常信息</param>
        public static void Fatal(object message, Exception exception = null)
        {
            Logger.Fatal(message, exception);
        }
        public static void FatalFormat(string format, params object[] args)
        {
            Logger.FatalFormat(format, args);
        }
        public static void FatalFormat(Exception exception, string format, params object[] args)
        {
            Logger.FatalFormat(format, args, exception);
        }
        public static void FatalFormat(IFormatProvider formatProvider, string format, params object[] args)
        {
            Logger.FatalFormat(formatProvider, format, args);
        }
        public static void FatalFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
        {
            Logger.FatalFormat(formatProvider, format, args, exception);
        }
        #endregion 
    }
}

原来的调用方式也改下:

Log4netHelper.Info("== Log4netHelper.Info ==");

 

posted on 2022-01-24 14:30  jack_Meng  阅读(827)  评论(0编辑  收藏  举报

导航