在项目中新建 “log4net.config” 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <log4net> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <File value="Log\" /> <!--是否是向文件中追加日志--> <AppendToFile value="true" /> <!--每个文件的大小--> <MaximumFileSize value="1MB"/> <!--log文件数--> <MaxSizeRollBackups value="10" /> <!--日志文件名是否是固定不变的--> <StaticLogFileName value="false" /> <!--日志文件名格式为:yyyy-MM-dd.log--> <DatePattern value="yyyy\\MM\\dd\\yyyy-MM-dd'.log'" /> <!--日志根据日期滚动--> <RollingStyle value="Date" /> <layout type="log4net.Layout.PatternLayout"> <ConversionPattern value="%date %logger [%thread] %level %message%newline" /> </layout> </appender> <root> <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) --> <level value="all" /> <appender-ref ref="RollingLogFileAppender" /> </root> </log4net> </configuration> |
配置好后在程序集 AssemblyInfo.cs 中加入
1 |
[assembly: log4net.Config.XmlConfigurator( ConfigFile = "log4net.config", Watch = true )] |
或者用代码初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 |
private void InitLog4net() { var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"); XmlConfigurator.ConfigureAndWatch(logCfg); //修改日志路径 var repository = LogManager.GetRepository(); var appenders = repository.GetAppenders(); var targetApder = appenders.First() as RollingFileAppender; targetApder.File = string.IsNullOrWhiteSpace(Settings.Default.LogPath) ? Path.Combine( Environment.CurrentDirectory,"log.txt") : Settings.Default.LogPath; targetApder.ActivateOptions(); this.log = LogManager.GetLogger("mainlog"); } |