C#log4net用法

发布时间 2023-08-24 22:34:28作者: 冰糖小袁子

新建一个名为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="false"/>
			<!--//是否追加到文件-->
			<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;&quot;yyyyMMddHH&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>

添加一个名为Log4NetHelper的类


    public class Log4NetHelper
    {

        private static readonly log4net.ILog _Logger4net = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        RichTextBox richTextBox;

        static Log4NetHelper _instance;

        public static Log4NetHelper Instance()
        {
            if (_instance == null)
            {
                _instance = new Log4NetHelper();
            }
            return _instance;
        }

        private Log4NetHelper()
        {
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string path = Path.Combine(baseDirectory, "log4net.config");
            XmlConfigurator.ConfigureAndWatch(new FileInfo(path));
        }

        public void Init(RichTextBox richTextBox)//该方法绑定需要显示日志的控件,这里绑定的是richtextbox
        {
            this.richTextBox = richTextBox;
        }
        #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 Debugf(string format, params object[] args)
        {
            if (this.IsDebugEnabled)
            {
                this.Log(LogLevel.Debug, format, args);
            }
        }

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

        #region [ Info ]

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

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

        #region  [ Warn ]


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

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

        #region  [ Error ]


        public void Errorf(string format, params object[] args)
        {
            if (this.IsErrorEnabled)
            {
                this.Log(LogLevel.Error, format, args);
                this.PrintLog(format, LogLevel.Error, System.Drawing.Color.Red);
            }
        }

        public void Errorf(string format, Exception exception, params object[] args)
        {
            if (this.IsErrorEnabled)
            {
                this.Log(LogLevel.Error, string.Format(format, args), exception);
                this.PrintLog(format, LogLevel.Error, System.Drawing.Color.Red);
            }
        }
        #endregion

        #region  [ Fatal ]


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

        public void Fatalf(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;
            }
        }

        private void PrintLog(string info, LogLevel level)
        {
            if (richTextBox != null)
            {
                var infoFomart = string.Format("{0}-[{1}]-{2}\r\n", DateTime.Now.ToString("yyyy-MM-dd-HH:mm:fff"), level, info);
                richTextBox.BeginInvoke(new Action(() =>
                {
                    richTextBox.AppendText(infoFomart);
                }));
            }
        }
        private void PrintLog(string info, LogLevel level, Color color)
        {
            if (richTextBox != null)
            {
                var infoFomart = string.Format("{0}-[{1}]-{2}\r\n", DateTime.Now.ToString("yyyy-MM-dd-HH:mm:fff"), level, info);
                richTextBox.BeginInvoke(new Action(() =>
                {
                    richTextBox.SelectionColor = color;
                    richTextBox.AppendText(infoFomart);
                }));
            }
        }
        #endregion
    }


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

winform用法,绑定richtextbox

 Log4NetHelper slog = Log4NetHelper.Instance();//声明对象

        private void Form1_Load(object sender, EventArgs e)
        {
            slog.Init(this.richTextBox1);//绑定需要显示日志的控件



            slog.Infof("程序加载完成");//书写日志
      
        }

注意事项:

复制到输出目录一定要改成始终复制!!!!!!!!!!!