winform程序利用Log4net记录日志

添加引用,可以用Nuget添加

AssemeblyInfo文件中添加如下语句:

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

app.Config 配置

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup> 
  <log4net>
    <logger name="Log">
      <level value="INFO" />
      <appender-ref ref="RollingLog" />
    </logger>
    <logger name="Err">
      <level value="ERROR" />
      <appender-ref ref="RollingErr" />
    </logger>
    <appender name="RollingLog" type="log4net.Appender.RollingFileAppender">
      <file value="WindowsServiceLog\" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <datePattern value="yyyyMMdd'.txt'" />
      <staticLogFileName value="false" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="记录时间:%d 线程ID:[%thread]- 操作信息:%m%n" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="INFO" />
        <param name="LevelMax" value="INFO" />
      </filter>
    </appender>
    <appender name="RollingErr" type="log4net.Appender.RollingFileAppender">
      <file value="Err\" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <datePattern value="yyyyMMdd'.txt'" />
      <staticLogFileName value="false" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="记录时间:%d 线程ID:[%thread]- 错误描述:%m%n" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="ERROR" />
        <param name="LevelMax" value="ERROR" />
      </filter>
    </appender>
  </log4net>
</configuration>

定义LogHelper类

using log4net;
using System.Diagnostics;
using System.Reflection;

namespace InformationApp
{
    public class LogHelper
    {
        private static readonly ILog logInfo = LogManager.GetLogger("Log");
        private static readonly ILog logErr = LogManager.GetLogger("Err");
        /// <summary>
        /// 记录正常的消息
        /// </summary>
        /// <param name="msg">消息内容</param>
        public static void info(string msg)
        {
            logInfo.Info(msg);
        }
        /// <summary>
        /// 记录异常信息
        /// </summary>
        /// <param name="msg">异常信息内容</param>
        public static void error(string msg)
        {
            StackTrace stackTrace = new StackTrace();
            StackFrame stackFrame = stackTrace.GetFrame(1);
            MethodBase methodBase = stackFrame.GetMethod();
            logErr.Error("类名:" + methodBase.ReflectedType.Name + " 方法名:" + methodBase.Name + " 信息:" + msg);
        }
    }
}

使用

 LogHelper.error(ex.Message);

赞(1)

评论 1

  1. #1

    来试试

    匿名4周前 (05-06)回复