log4net 使用笔记(c# .net framework)

  1. 通过nuget添加引用
  2. 添加log4net.config配置文件

<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  configSections>

  <log4net>
    
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" />
    appender>

    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      
      <file value="logfile/" />
      
      <appendToFile value="true" />

      
      

      
      <rollingStyle value="Composite" />

      
      <datePattern value="yyyyMMdd".log"" />

      
      <maxSizeRollBackups value="10" />

      
      <maximumFileSize value="2MB" />
      

      
      <staticLogFileName value="false" />

      <layout type="log4net.Layout.PatternLayout">
        
        <conversionPattern value="[%date]  %thread -- %-5level -- %logger [%M] -- %message%newline" />
      layout>
    appender>
    <root>
      
      
      <level value="ALL" />
      
      

      
      <appender-ref ref="RollingLogFileAppender" />
    root>
  log4net>
configuration>
  1. 项目Properties\AssemblyInfo.cs文件中添加配置(wpf中不能这样使用,提示错误:error MC1000: 未知的生成错误“因为没有预加载,所以无法解析程序集“log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a”的依赖项。在使用 ReflectionOnly API 时,必须通过 ReflectionOnlyAssemblyResolve 事件预加载或按需要加载依赖程序集。”
/*winform*/
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
  1. 编写代码
using System;
using log4net;

namespace Utilities
{
    public class LogHelper
    {
        static LogHelper()
        {
            log4net.Config.XmlConfigurator.ConfigureAndWatch(
                new System.IO.FileInfo("log4net.config"));

            log = LogManager.GetLogger("DefaultLogger");
        }
        public static log4net.ILog log =null;

        public static void Info(string msg, Type type)
        {
            Info(string.Format("{0} - {1}", type.Name, msg));
        }

        public static void Info(string msg)
        {
            log.Info(msg);
        }

        public static void Error(string msg, Exception ex, Type type)
        {
            Error(string.Format("{0} - {1}", type.Name, msg), ex);
        }

        public static void Error(string msg, Exception ex)
        {
            log.Error(msg, ex);
        }

        public static void Debug(string msg, Type type)
        {
            Debug(string.Format("{0} - {1}", type.Name, msg));
        }

        public static void Debug(string msg)
        {
            log.Debug(msg);
        }
    }
}

你可能感兴趣的:(C#,log4net,log4net,c#)