项目中利用Log4net记录日志还是比较方便的,我也按照网上的一些操作进行了实践
参考文章 1:Log4Net使用指南 2:LOG4NET日志配置
组件下载 log4net组件下载
1:设置配置文件,这里我是自己新建的xml,网站下log4net.config
这里面有2个类别的log,error和info,配置的路径不一样
<?xml version="1.0"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> </configSections> <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/ErrorLog.log" /> <param name="AppendToFile" value="true" /> <param name="MaxSizeRollBackups" value="100" /> <param name="MaximumFileSize" value="1MB" /> <param name="RollingStyle" value="Size" /> <param name="StaticLogFileName" value="true" /> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%-5p %d [%c] %m%n" /> </layout> </appender> <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="log/InfoLog.log" /> <param name="AppendToFile" value="true" /> <param name="MaxSizeRollBackups" value="100" /> <param name="MaximumFileSize" value="1MB" /> <param name="RollingStyle" value="Size" /> <param name="StaticLogFileName" value="true" /> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%-5p %d [%c] %m%n" /> </layout> </appender> </log4net> </configuration>
2:设置帮助类LogHelper
这里的logger name和配置文件的名称对应
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace xsFramework.function.Log4Net { public class LogHelper { //log4net日志专用 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); } /// <summary> /// 普通的文件记录日志 /// </summary> /// <param name="info"></param> public static void WriteLog(string info) { if (loginfo.IsInfoEnabled) { loginfo.Info(info); } } /// <summary> /// 错误日志 /// </summary> /// <param name="info"></param> /// <param name="se"></param> public static void WriteLog(string info, Exception se) { if (logerror.IsErrorEnabled) { logerror.Error(info, se); } } } }
3:在程序启动是进行开启和配置,也可以不设置路径,但是要在当前项目的配置文件中,并且是在最上面
protected void Application_Start(object sender, EventArgs e) { FileInfo file = new FileInfo(Server.MapPath("~/log4net.config")); LogHelper.SetConfig(file); }
4:使用过程
LogHelper.WriteLog("提示信息"); LogHelper.WriteLog("錯誤信息", new Exception());
这里就可以开始记录了,也可以设置多个类别,但是我感觉简单的网站就记录提示信息和错误信息即可...