1.在程序的assembly.cs下添加: [assembly: log4net.Config.XmlConfigurator(Watch = true)] (忘记这一步,弄了半天,上次好像也是这样,不常用还是记录下好)
对于log配置参数读取可制定config文件: [assembly: XmlConfigurator(ConfigFile="Log4net.config",Watch=true)] //此处读取config就是读取log4net.config的文件;
2.程序引用log4net,定义记录Log的实例 : ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().GetType());
注意:如果程序是windows服务,那么需要将 log4net的配置文件放到app.config目录下;
3.配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- Register a section handler for the log4net section -->
<configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
</configSections>
<!-- This section contains the log4net configuration settings -->
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log\\" />
<!-- Example using environment variables in params -->
<!-- <file value="${TMP}\log-file.txt" /> -->
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd".txt"" />
<StaticLogFileName value="false"/>
<!-- An alternate output encoding can be specified -->
<!-- <encoding value="unicodeFFFE" /> -->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %m%n" />
</layout>
<!-- Alternate layout using XML
<layout type="log4net.Layout.XMLLayout" /> -->
</appender>
<appender name="TraceAppender" type="log4net.Appender.TraceAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date-->%m%n" />
</layout>
</appender>
<!-- Setup the root category, add the appenders and set the default level -->
<root>
<!--记录日志的级别,ALL是记录所有的,debug,info,warn,error-->
<level value="ALL" />
<appender-ref ref="LogFileAppender" />
<!--appender-ref ref="TraceAppender" /-->
</root>
</log4net>
</configuration>