一、Web项目中加入log4net:
1、nuget中加入log4net
2、webconfig中的<configuration></configuration>中加入以下节点:
<configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> </configSections> <log4net> <root> <level value="INFO" /> <appender-ref ref="FileAppender" /> <appender-ref ref="ConsoleAppender" /> </root> <appender name="FileAppender" type="log4net.Appender.RollingFileAppender"> <file value="logs\" /> <appendToFile value="true" /> <rollingStyle value="Composite" /> <datePattern value="yyyy-MM-dd'.txt'" /> <maxSizeRollBackups value="200" /> <maximumFileSize value="10485760" /> <staticLogFileName value="false" /> <layout type="log4net.Layout.PatternLayout"> <header value="[Header] " /> <footer value="[Footer] " /> <conversionPattern value="%date %-5level %logger - %message%newline" /> </layout> </appender> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" /> </layout> </appender> </log4net>
3、在Global.asax.cs中加入:
log4net.Config.XmlConfigurator.Configure();
二、控制台中加入log4net
1、app.config中加入节点:
<configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> </configSections> <log4net> <root> <level value="INFO" /> <appender-ref ref="FileAppender" /> <appender-ref ref="ConsoleAppender" /> </root> <appender name="FileAppender" type="log4net.Appender.RollingFileAppender"> <file value="logs\" /> <appendToFile value="true" /> <rollingStyle value="Composite" /> <datePattern value="yyyy-MM-dd'.txt'" /> <maxSizeRollBackups value="200" /> <maximumFileSize value="10485760" /> <staticLogFileName value="false" /> <layout type="log4net.Layout.PatternLayout"> <header value="[Header] " /> <footer value="[Footer] " /> <conversionPattern value="%date %-5level %logger - %message%newline" /> </layout> </appender> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" /> </layout> </appender> </log4net>
2、AssemblyInfo.cs 中最后加入这句:
[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]
3、实际使用:
log4net.ILog logInfo = log4net.LogManager.GetLogger("loginfo"); logInfo.Info("测试日志写入"); Console.WriteLine("日志写入文件完成"); Console.ReadLine();