在winform项目里集成log4net日志控件
1、引用log4net.dll文件 备注:通过直接引用dll或使用nugit都可以
2、添加一个log4net.config文件,内容如下:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> </configSections> <log4net> <root> </root> <logger name="Error"> <level value="ALL" /> <appender-ref ref="ErrorAppender" /> </logger> <logger name="InfoLog"> <level value="ALL" /> <appender-ref ref="InfoAppender" /> </logger> <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender,log4net" > <param name="File" type="" value="Log/Error/" /> <param name="AppendToFile" value="true" /> <param name="RollingStyle" value="Date" /> <param name="DatePattern" value="yyyyMMdd" /> <param name="StaticLogFileName" value="false" /> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%n[%d] %c %n%m%n%n" /> <param name="Header" value="-----------BEGIN-----------" /> <param name="Footer" value="------------END------------" /> </layout> </appender> <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender,log4net" > <param name="File" type="" value="Log/Info/" /> <param name="AppendToFile" value="true" /> <param name="RollingStyle" value="Date" /> <param name="DatePattern" value="yyyyMMdd" /> <param name="StaticLogFileName" value="false" /> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%n[%d] %c %n%m%n%n" /> <param name="Header" value="-----------BEGIN-----------" /> <param name="Footer" value="------------END------------" /> </layout> </appender> </log4net> </configuration>
注意:在这个config文件上点右键属性,让它始终复制或较新复制
3、在Properties下的AssemblyInfo.cs文件时加一行:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
4、加一个Help类内容如下:
public class log4netHelper { /// <summary> /// 普通日志 /// </summary> /// <param name="message">日志内容</param> public static void Info(string message) { log4net.ILog log = log4net.LogManager.GetLogger("InfoLog"); if (log.IsInfoEnabled) { log.Info(message); } log = null; } /// <summary> /// 错误日志 /// </summary> /// <param name="message">错误日志</param> public static void Error(string message) { log4net.ILog log = log4net.LogManager.GetLogger("Error"); if (log.IsInfoEnabled) { log.Error(message); } log = null; } }
5、使用示例如下:
log4netHelper.Info("这是一条普通日志"); log4netHelper.Error("这是一条错误日志");