具体方法如下:
一、App.config配置
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="System.Configuration.IgnoreSectionHandler" /> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <appSettings> <!--压缩文件解压路径--> <add value="D:FileCompare" key="FileCompare"/> </appSettings> <log4net> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="ErrorlogsErrorLog.txt"/> <param name="AppendToFile" value="true"/> <param name="MaxSizeRollBackups" value="30"/> <param name="MaximumFileSize" value="8096KB"/> <param name="RollingStyle" value="Size"/> <param name="StaticLogFileName" value="true"/> <layout type="log4net.Layout.PatternLayout"> <!--<param name="Header" value="[Header] "/> <param name="Footer" value="[Footer] "/>--> <param name="ConversionPattern" value="%d %-5p %c %m%n"/> </layout> </appender> <root> <level value="ALL"/> <appender-ref ref="RollingLogFileAppender"/> </root> </log4net> </configuration>
二、form.cs中调用:初始化Log
private void btnSelect_Click(object sender, EventArgs e) { ILog log = LogManager.GetLogger("Error"); }
三、Assmbely.cs配置
//[assembly: log4net.Config.XmlConfigurator(Watch = true, ConfigFile = "Log4Net.config")] // 日志组件配置 //[assembly: log4net.Config.DOMConfigurator(ConfigFile = "Log4Net.config", Watch = true)] [assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]
别忘了引入log4net.dll
如果出现“App.config提示错误“配置系统未能初始化”
解决方案:
"如果配置文件中包含 configSections 元素,则 configSections 元素必须是 configuration 元素的第一个子元素。"所以它前面如果有connectionStrings或其它节点,必须把connectionStrings放到它的后面。
WebForm 配置log4net
Global.asax
// log4net日志配置 FileInfo file = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "Log4Net.config"); log4net.Config.XmlConfigurator.Configure(file); // end of log4net日志配置