图片 4

WPF使用Log4net.dll库的demo(转载加个人观点)

1.NuGet包管理器中安装log4net

图片 1

  

2.接着在项目中添加log4net.config文件,以及手撸或寻找一个LogHelper

 

添加完log4net.config一定要设置属性,将其始终复制到输出目录

  • 3.添加log4net.config配置文件:

图片 2

 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
  </configSections>
  <log4net>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="log\logfile.log"/>
      <appendToFile value="true"/>
      <rollingStyle value="Composite"/>
      <datePattern value="yyyyMMdd"/>
      <maxSizeRollBackups value="10"/>
      <maximumFileSize value="1MB"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
      </layout>
    </appender>
    <root>
      <level value="All"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </root>
  </log4net>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
  </startup>
</configuration>
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net xsi:noNamespaceSchemaLocation="http://csharptest.net/downloads/schema/log4net.xsd"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <root>
      <level value="DEBUG"/>
      <appender-ref ref="ErrorRollingFileAppender"/>
      <appender-ref ref="WarnRollingFileAppender"/>
      <appender-ref ref="InfoRollingFileAppender"/>
      <appender-ref ref="DebugRollingFileAppender"/>
    </root>

    <!--一般错误日志定义,用于记录已知需处理的与未捕获的异常-->
    <!--日志输出格式:[时间]:类名 线程号 消息-->
    <appender name="ErrorRollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="ERROR"/>
        <levelMax value="FATAL"/>
      </filter>
      <filter type="log4net.Filter.DenyAllFilter"/>
      <file value="logs\"/>
      <rollingStyle value="Date"/>
      <datePattern value="yyyy-MM-dd\\&quot;Error.log&quot;"/>
      <staticLogFileName value="false"/>
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="[%d{yyyy-MM-dd HH:mm:ss.fff}] %-5p %c.%M %t %n%m%n"/>
      </layout>
    </appender>

    <!--警告日志定义,用于记录已知不需处理的异常,系统警告信息-->
    <!--日志输出格式:[时间]:类名 线程号 消息-->
    <appender name="WarnRollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <filter type="log4net.Filter.LevelMatchFilter">
        <levelToMatch value="WARN"/>
      </filter>
      <filter type="log4net.Filter.DenyAllFilter"/>
      <file value="logs\"/>
      <appendToFile value="true"/>
      <rollingStyle value="Date"/>
      <datePattern value="yyyy-MM-dd\\&quot;Warn.log&quot;"/>
      <staticLogFileName value="false"/>
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="[%d{yyyy-MM-dd HH:mm:ss.fff}] %c.%M %t %m%n"/>
      </layout>
    </appender>

    <!--信息日志定义,用于记录用户相关信息-->
    <!--日志输出格式:[时间]:消息-->
    <appender name="InfoRollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <filter type="log4net.Filter.LevelMatchFilter">
        <levelToMatch value="INFO"/>
      </filter>
      <filter type="log4net.Filter.DenyAllFilter"/>
      <file value="logs\"/>
      <appendToFile value="true"/>
      <rollingStyle value="Date"/>
      <datePattern value="yyyy-MM-dd\\&quot;Info.log&quot;"/>
      <staticLogFileName value="false"/>
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="[%d{yyyy-MM-dd HH:mm:ss}] %m%n"/>
      </layout>
    </appender>

    <!--信息日志定义,用于收集开发调试信息-->
    <!--日志输出格式:[时间]:类名 线程号 消息-->
    <appender name="DebugRollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <filter type="log4net.Filter.LevelMatchFilter">
        <levelToMatch value="DEBUG"/>
      </filter>
      <filter type="log4net.Filter.DenyAllFilter"/>
      <file value="logs\"/>
      <appendToFile value="true"/>
      <rollingStyle value="Date"/>
      <datePattern value="yyyy-MM-dd\\&quot;Debug.log&quot;"/>
      <staticLogFileName value="false"/>
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="[%d{yyyy-MM-dd HH:mm:ss.fff}] %c %t:%m%n"/>
      </layout>
    </appender>

  </log4net>
</configuration>

  

 

 

 1     public static class LogHelper
 2     {
 3         private static readonly log4net.ILog Logerror = log4net.LogManager.GetLogger("DEBUG");
 4 
 5         public static void WriteInfoLog(string info)
 6         {
 7             Logerror.Info(info);
 8         }
 9 
10         public static void WriteErrorLog(string info)
11         {
12             Logerror.Error(info);
13         }
14 
15         public static void WriteDebugLog(string info)
16         {
17             Logerror.Debug(info);
18         }
19 
20         public static void WriteDebugLog(Exception exception)
21         {
22             Logerror.Debug(exception.Message, exception);
23         }
24     }
  • 4.添加一个公共的日志管理类AppLog.cs

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

 3.最后需要在AssemblyInfo.cs中添加一行代码

namespace log4net
{
    /// <summary>
    /// 使用Log4net插件的log日志对象
    /// </summary>
    public static class AppLog
    {
        private static ILog log;

        static AppLog()
        {
            XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile));
            log = LogManager.GetLogger(typeof(AppLog));
        }

        public static void Debug(object message)
        {
            log.Debug(message);
        }

        public static void DebugFormatted(string format, params object[] args)
        {
            log.DebugFormat(format, args);
        }

        public static void Info(object message)
        {
            log.Info(message);
        }

        public static void InfoFormatted(string format, params object[] args)
        {
            log.InfoFormat(format, args);
        }

        public static void Warn(object message)
        {
            log.Warn(message);
        }

        public static void Warn(object message, Exception exception)
        {
            log.Warn(message, exception);
        }

        public static void WarnFormatted(string format, params object[] args)
        {
            log.WarnFormat(format, args);
        }

        public static void Error(object message)
        {
            log.Error(message);
        }

        public static void Error(object message, Exception exception)
        {
            log.Error(message, exception);
        }

        public static void ErrorFormatted(string format, params object[] args)
        {
            log.ErrorFormat(format, args);
        }

        public static void Fatal(object message)
        {
            log.Fatal(message);
        }

        public static void Fatal(object message, Exception exception)
        {
            log.Fatal(message, exception);
        }

        public static void FatalFormatted(string format, params object[] args)
        {
            log.FatalFormat(format, args);
        }
    }
}

 图片 3

  • 5.在任何你想写日志的地方使用,例如:

    AppLog.Info(“Info log”);
    AppLog.Error(“Error log”);

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

  

效果如下:


1         static void Main(string[] args)
2         {
3             LogHelper.WriteDebugLog("1234444445");
4         }
  • 6.经验之谈:不要把项目名称起为log4net,或任何数字在中间的名称,否则引入log4net.dll的时候就会直接报错
  • **7.当运行正常没有创建日志文件或者log =
    LogManager.GetLogger(typeof(AppLog))中log对象字段值为false时,右击log4net.config选择属性**–>高级把复制到项目的值改为始终复制**
  •  8  类库项目中好像不能实现此打印日志功能,

图片 4

 

Demo下载:https://pan.baidu.com/s/1hFXoUPZUWVCwDdjx-bTtHQ