1.引用log4net库类
2.写配置,我一般是写在web.config
<configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> </configSections> <log4net debug="true"> <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender"> <filter type="log4net.Filter.LevelMatchFilter"> <levelToMatch value="ERROR" /> </filter> <filter type="log4net.Filter.DenyAllFilter" /> <!--日志文件名开头--> <file value="..\\Logs\\Error\\" /> <!--是否追加到文件--> <appendToFile value="true" /> <!--混合使用日期和文件大小变换日志文件名--> <rollingStyle value="Composite" /> <!--最大变换数量--> <maxSizeRollBackups value="10"/> <!--最大文件大小--> <maximumFileSize value="500KB"/> <!--日期的格式--> <staticLogFileName value="false" /> <datePattern value="yyyyMMdd".log"" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date %logger : %message%newline" /> </layout> </appender> <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender"> <filter type="log4net.Filter.LevelMatchFilter"> <levelToMatch value="INFO" /> </filter> <filter type="log4net.Filter.DenyAllFilter" /> <!--日志文件名开头--> <file value="..\\Logs\\Info\\" /> <!--是否追加到文件--> <appendToFile value="true" /> <!--混合使用日期和文件大小变换日志文件名--> <rollingStyle value="Composite" /> <!--最大变换数量--> <maxSizeRollBackups value="10"/> <!--最大文件大小--> <maximumFileSize value="500KB"/> <!--日期的格式--> <staticLogFileName value="false" /> <datePattern value="yyyyMMdd".log"" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date %logger : %message%newline" /> </layout> </appender> <root> <level value="All" /> <appender-ref ref="ErrorAppender" /> <appender-ref ref="InfoAppender" /> </root> </log4net>
3.在项目的AssemblyInfo最后加上[
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]
4.在Application_Start()中加上
string l4net = Server.MapPath("~/Web.config"); log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(l4net));