Windows c# 使用log4net记录日志

1、下载引入log4net包,不会下载的同学可以参考https://blog.csdn.net/qq_37243144/article/details/107357638

2、导入配置文件

新建log4net.config,将以下配置复制进去

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <log4net>
    <!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
    <!-- Set root logger level to ERROR and its appenders -->
    <root>
      <level value="ALL"/>
      <appender-ref ref="SysAppender"/>
    </root>
    <!-- Print only messages of level DEBUG or above in the packages -->
    <logger name="WebLogger">
      <level value="ALL"/>
    </logger>
    <appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net">
      <!-- name属性指定其名称,type则是log4net.Appender命名空间的一个类的名称,意思是,指定使用哪种介质-->
      <param name="File" value="Logger\"/>
      <!--//日志存放位置(这里的value值是一个Logger,表示在项目文件夹中创建一个名叫Logger的文件。也可以是value="c:\log.txt")-->
      <param name="AppendToFile" value="true"/>
      <!--//是否追加到文件-->
      <param name="MaxSizeRollBackups" value="100" />
      <!--备份文件的个数-->
      <param name="MaxFileSize" value="10240" />
      <!--当个日志文件的最大大小-->
      <param name="StaticLogFileName" value="false" />
      <!--是否使用静态文件名-->
      <param name="RollingStyle" value="Date"/>
      <!--//变换的形式为日期-->
      <param name="DatePattern" value="&quot;Logs_&quot;yyyyMMdd&quot;.txt&quot;"/>
      <!--//生成格式;每天生成一个日志-->
      <param name="StaticLogFileName" value="false"/>
      <!--//日志文件名,是否固定不变-->
      <layout type="log4net.Layout.PatternLayout,log4net">
        <!--错误日志布局-->
        <!--<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n"/>-->
        <param name="ConversionPattern" value="%d [%t] [%-5p] - %m%n"/>
        <!--
          %m(message):输出的日志消息,如ILog.Debug(…)输出的一条消息 
          %n(new line):换行 
          %d(datetime):输出当前语句运行的时刻 
          %r(run time):输出程序从运行到执行到当前语句时消耗的毫秒数 
          %t(thread id):当前语句所在的线程ID 
          %p(priority): 日志的当前优先级别,即DEBUG、INFO、WARN…等 
          %c(class):当前日志对象的名称,例如: 
          %f(file):输出语句所在的文件名。 
          %l(line):输出语句所在的行号。 
          %数字:表示该项的最小长度,如果不够,则用空格填充,如“%-5level”表示level的最小宽度是5个字符,如果实际长度不够5个字符则以空格填充。
        -->
      </layout>
    </appender>
    <!--//这种配置,是将日志写入到文本文件当中-->
  </log4net>
</configuration>

3、打开AssemblyInfo.cs,加入下面这行代码进去

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

 3、自定义一个日志帮助类LogHelper,将以下代码复制进去

using System;
using System.Reflection;

namespace Util
{
    /// <summary>
    /// Author     :TonyKit
    /// Date       :2016-09-25
    /// Description:日志辅助类
    /// [assembly: log4net.Config.XmlConfigurator(ConfigFile = "config/log4net.config", ConfigFileExtension = "config", Watch = true)]
    /// </summary>
    public class LogHelper
    {
        #region [ 单例模式 ]
        private static readonly LogHelper _logger = new LogHelper();
        private static readonly log4net.ILog _Logger4net = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// 无参私有构造函数
        /// </summary>
        private LogHelper()
        {
        }

        /// <summary>
        /// 得到单例
        /// </summary>
        public static LogHelper Singleton
        {
            get
            {
                return _logger;
            }
        }
        #endregion

        #region [ 参数 ]
        public bool IsDebugEnabled
        {
            get { return _Logger4net.IsDebugEnabled; }
        }
        public bool IsInfoEnabled
        {
            get { return _Logger4net.IsInfoEnabled; }
        }
        public bool IsWarnEnabled
        {
            get { return _Logger4net.IsWarnEnabled; }
        }
        public bool IsErrorEnabled
        {
            get { return _Logger4net.IsErrorEnabled; }
        }
        public bool IsFatalEnabled
        {
            get { return _Logger4net.IsFatalEnabled; }
        }
        #endregion

        #region [ 接口方法 ]

        #region [ Debug ]
        public void Debug(string message)
        {
            if (this.IsDebugEnabled)
            {
                this.Log(LogLevel.Debug, message);
            }
        }

        public void Debug(string message, Exception exception)
        {
            if (this.IsDebugEnabled)
            {
                this.Log(LogLevel.Debug, message, exception);
            }
        }

        public void DebugFormat(string format, params object[] args)
        {
            if (this.IsDebugEnabled)
            {
                this.Log(LogLevel.Debug, format, args);
            }
        }

        public void DebugFormat(string format, Exception exception, params object[] args)
        {
            if (this.IsDebugEnabled)
            {
                this.Log(LogLevel.Debug, string.Format(format, args), exception);
            }
        }
        #endregion

        #region [ Info ]
        public void Info(string message)
        {
            if (this.IsInfoEnabled)
            {
                this.Log(LogLevel.Info, message);
            }
        }

        public void Info(string message, Exception exception)
        {
            if (this.IsInfoEnabled)
            {
                this.Log(LogLevel.Info, message, exception);
            }
        }

        public void InfoFormat(string format, params object[] args)
        {
            if (this.IsInfoEnabled)
            {
                this.Log(LogLevel.Info, format, args);
            }
        }

        public void InfoFormat(string format, Exception exception, params object[] args)
        {
            if (this.IsInfoEnabled)
            {
                this.Log(LogLevel.Info, string.Format(format, args), exception);
            }
        }
        #endregion

        #region  [ Warn ]

        public void Warn(string message)
        {
            if (this.IsWarnEnabled)
            {
                this.Log(LogLevel.Warn, message);
            }
        }

        public void Warn(string message, Exception exception)
        {
            if (this.IsWarnEnabled)
            {
                this.Log(LogLevel.Warn, message, exception);
            }
        }

        public void WarnFormat(string format, params object[] args)
        {
            if (this.IsWarnEnabled)
            {
                this.Log(LogLevel.Warn, format, args);
            }
        }

        public void WarnFormat(string format, Exception exception, params object[] args)
        {
            if (this.IsWarnEnabled)
            {
                this.Log(LogLevel.Warn, string.Format(format, args), exception);
            }
        }
        #endregion

        #region  [ Error ]

        public void Error(string message)
        {
            if (this.IsErrorEnabled)
            {
                this.Log(LogLevel.Error, message);
            }
        }

        public void Error(string message, Exception exception)
        {
            if (this.IsErrorEnabled)
            {
                this.Log(LogLevel.Error, message, exception);
            }
        }

        public void ErrorFormat(string format, params object[] args)
        {
            if (this.IsErrorEnabled)
            {
                this.Log(LogLevel.Error, format, args);
            }
        }

        public void ErrorFormat(string format, Exception exception, params object[] args)
        {
            if (this.IsErrorEnabled)
            {
                this.Log(LogLevel.Error, string.Format(format, args), exception);
            }
        }
        #endregion

        #region  [ Fatal ]

        public void Fatal(string message)
        {
            if (this.IsFatalEnabled)
            {
                this.Log(LogLevel.Fatal, message);
            }
        }

        public void Fatal(string message, Exception exception)
        {
            if (this.IsFatalEnabled)
            {
                this.Log(LogLevel.Fatal, message, exception);
            }
        }

        public void FatalFormat(string format, params object[] args)
        {
            if (this.IsFatalEnabled)
            {
                this.Log(LogLevel.Fatal, format, args);
            }
        }

        public void FatalFormat(string format, Exception exception, params object[] args)
        {
            if (this.IsFatalEnabled)
            {
                this.Log(LogLevel.Fatal, string.Format(format, args), exception);
            }
        }
        #endregion
        #endregion

        #region [ 内部方法 ]
        /// <summary>
        /// 输出普通日志
        /// </summary>
        /// <param name="level"></param>
        /// <param name="format"></param>
        /// <param name="args"></param>
        private void Log(LogLevel level, string format, params object[] args)
        {
            switch (level)
            {
                case LogLevel.Debug:
                    _Logger4net.DebugFormat(format, args);
                    break;
                case LogLevel.Info:
                    _Logger4net.InfoFormat(format, args);
                    break;
                case LogLevel.Warn:
                    _Logger4net.WarnFormat(format, args);
                    break;
                case LogLevel.Error:
                    _Logger4net.ErrorFormat(format, args);
                    break;
                case LogLevel.Fatal:
                    _Logger4net.FatalFormat(format, args);
                    break;
            }
        }

        /// <summary>
        /// 格式化输出异常信息
        /// </summary>
        /// <param name="level"></param>
        /// <param name="message"></param>
        /// <param name="exception"></param>
        private void Log(LogLevel level, string message, Exception exception)
        {
            switch (level)
            {
                case LogLevel.Debug:
                    _Logger4net.Debug(message, exception);
                    break;
                case LogLevel.Info:
                    _Logger4net.Info(message, exception);
                    break;
                case LogLevel.Warn:
                    _Logger4net.Warn(message, exception);
                    break;
                case LogLevel.Error:
                    _Logger4net.Error(message, exception);
                    break;
                case LogLevel.Fatal:
                    _Logger4net.Fatal(message, exception);
                    break;
            }
        }
        #endregion
    }


    #region [ enum: LogLevel ]
    /// <summary>
    /// 日志级别
    /// </summary>
    public enum LogLevel
    {
        Debug,
        Info,
        Warn,
        Error,
        Fatal
    }
    #endregion
}

该代码是我从某大神哪里拷贝过来的,个人觉得很好用,但忘记从哪里拷贝过来的了,有人知道的话帮忙留个连接,我新加上

4、打印日志测试

using ConsoleApp1;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ClassLibrary1;
using System.IO;
using SuperSocket.ClientEngine;
using Util;

namespace ConsoleApp1
{
    class Program
    {

        static void Main(string[] args)
        {
            LogHelper.Singleton.Debug("test");
            LogHelper.Singleton.Error("test");
            LogHelper.Singleton.Fatal("test");
            LogHelper.Singleton.Info("test");
            LogHelper.Singleton.Warn("test");

            Console.ReadKey();
        }
    }
}

日志会打印在步骤2配置的地方,效果如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值