1.nuget 中安装log4net
2。添加一个配置文件“log4net2.config”,内容如下:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net debug="true"> <appender name="RollingFile" type="log4net.Appender.RollingFileAppender"> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <File value="logs"/> <AppendToFile value="true" /> <rollingStyle value="Composite" /> <MaxSizeRollBackups value="999" /> <MaximumFileSize value="9000KB" /> <StaticLogFileName value="false" /> <DatePattern value="''yyyy-MM-dd'.log'" /> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%-5p %d %5rms [%t] %-8.22c{1} %-2.18M - %m%n" /> <param name="Footer" value=" " /> </layout> </appender> <root> <level value="All" /> <appender-ref ref="RollingFile"/> </root> </log4net> </configuration>
MaximumFileSize value="9000KB",日志文件大小超过9000KB就产生一个新文件。避免单个文件过大,打开困难。
MaxSizeRollBackups value="999",日志文件名序号从1到999。这2项根据实际情况调整。
3,代码中初始化配置
string logCfg = Path.Combine(Application.StartupPath, "log4net2.config"); XmlConfigurator.Configure(new FileInfo(logCfg));
4,写入日志
log4net.ILog log = log4net.LogManager.GetLogger("testApp.Logging");//获取一个日志记录器 log.Info(DateTime.Now.ToString() + ": login success");//写入一条新log
一般会对ILog的实例封装成公共类。