1.Install-Package log4net
2.命名空间前添加XmlConfiguratorAttribute标记:[assembly: log4net.Config.XmlConfigurator(Watch = true)],或添加到AssemblyInfo.cs
3.web.config配置
在<configuration></configuration>里添加,
<configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> <section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" /> </configSections> <log4net> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <!--日志路径--> <param name= "File" value= "D:\log\"/> <!--是否是向文件中追加日志--> <param name= "AppendToFile" value= "true"/> <!--log保留天数--> <param name= "MaxSizeRollBackups" value= "10"/> <!--日志文件名是否是固定不变的--> <param name= "StaticLogFileName" value= "false"/> <!--日志文件名格式为:2017-07-25.log--> <param name= "DatePattern" value= "yyyy-MM-dd".log""/> <!--日志根据日期滚动--> <param name= "RollingStyle" value= "Date"/> <!--日志文本格式--> <layout type="log4net.Layout.PatternLayout"> <!--例:2017-07-25 10:56:15,506 [9] INFO Log4NetSample.Program 18 - 消息 --> <!--%d 时间--> <!--%t 线程--> <!--%-5p 日志级别--> <!--%c 出错类--> <!--%L 出错行--> <!--%m 日志信息--> <!--%n 换行--> <param name="ConversionPattern" value="%d [%t] %-5p %c %L - %m %n" /> </layout> </appender> <root> <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) --> <level value="all" /> <appender-ref ref="RollingLogFileAppender"/> </root> </log4net>
4.使用
var log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); log.Info("消息"); log.Warn("警告"); log.Error("异常"); log.Fatal("错误");
5.结果
参考https://www.cnblogs.com/Answer-Geng/p/7229155.html