1、首先在项目中添加Nuget程序包...
2、然后在NuGet窗体中搜索Log4Net,然后点击安装<安装过程可能会持续几分钟,请耐心等待>
3、在项目中添加一个Config文件,如已有App.config,则直接在其中添加内容:
截图中配置的XML代码如下:
<log4net> <logger name="logerror"> <level value="ERROR" /> <appender-ref ref="ErrorAppender" /> </logger> <logger name="loginfo"> <level value="INFO" /> <appender-ref ref="InfoAppender" /> </logger> <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="Log\LogError\" /> <param name="AppendToFile" value="true" /> <param name="MaxSizeRollBackups" value="100" /> <param name="MaxFileSize" value="10240" /> <param name="StaticLogFileName" value="false" /> <param name="DatePattern" value="yyyyMMdd".txt"" /> <param name="RollingStyle" value="Date" /> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%n异常时间:%d %n异常级别:%-5p%n异常内容:%m%n" /> </layout> <!--< > = <> %n = 回车--> </appender> <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="Log\LogInfo\" /> <param name="AppendToFile" value="true" /> <param name="MaxFileSize" value="10240" /> <param name="MaxSizeRollBackups" value="100" /> <param name="StaticLogFileName" value="false" /> <param name="DatePattern" value="yyyyMMdd".txt"" /> <param name="RollingStyle" value="Date" /> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="日志时间:%d %n日志级别:%-5p %n日志内容:%m%n%n" /> </layout> </appender> </log4net>
最后在项目的 AssemblyInfo.cs 文件中注册Config文件,如下:
//为项目注册Log4Net.config配置文件
[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]
最后,添加日志类:
public class LogHelper { private LogHelper() { } public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo"); public static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror"); public static void SetConfig() { log4net.Config.XmlConfigurator.Configure(); } public static void SetConfig(FileInfo configFile) { log4net.Config.XmlConfigurator.Configure(configFile); } public static void WriteLog(string info) { if (loginfo.IsInfoEnabled) { loginfo.Info(info); } } public static void WriteLog(string info, Exception se) { if (logerror.IsErrorEnabled) { logerror.Error(info, se); } } }
好了,到了这里,准备工作也就完成了,下面我们就开始测试下吧
日志文件默认记录在根目录下,在config中可以更改路径