- 下载 https://logging.apache.org/log4net/download_log4net.cgi,或NuGet搜索“log4net”。
- 修改配置文件
1 <?xml version="1.0" encoding="utf-8"?> 2 <configuration> 3 <configSections> 4 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> 5 </configSections> 6 <log4net> 7 <appender name="RollingLogFileAppender_DateFormat" type="log4net.Appender.RollingFileAppender"> 8 <file value="LogsLog_" /> 9 <appendToFile value="true" /> 10 <rollingStyle value="Date" /> 11 <datePattern value="yyyyMMdd'.txt'" /> 12 <staticLogFileName value="false"/> 13 <layout type="log4net.Layout.PatternLayout"> 14 <footer value="————————————————————————————————————————————————————————————"/> 15 <conversionPattern value="%n【日志级别】%-5level 16 %n【记录时间】%date 17 %n【线程编号】[%thread] 18 %n【执行时间】[%r]毫秒 19 %n【出错文件】%file 20 %n【出错行号】%line 21 %n【错误描述】%message 22 %n【错误详情】" /> 23 </layout> 24 </appender> 25 <root> 26 <appender-ref ref="RollingLogFileAppender_DateFormat" /> 27 </root> 28 </log4net> 29 </configuration>
注意:configSections 节点,一点要放到 configuration 下第一个。
- 代码中添加 [assembly: log4net.Config.XmlConfigurator(Watch = true)],这么一行。我放在AssemblyInfo.cs里了。
- 代码:
1 ILog Logger = LogManager.GetLogger("XXX"); 2 //log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); 3 try 4 { 5 6 } 7 catch (Exception e) 8 { 9 Program.Logger.Error("错误描述", e); 10 }