Log4net是Apache log4j框架在Microsort.NET平台实现的框架.
帮助程序员将日志信息输出到各种目标(控制台,数据库,文件等)
1.新建一个ASP.NET项目
文件,用来放置日志的配置,为什么不写在在web.Config中呢,主要是因为这样更加清晰,明了,不会那么的混乱
打开log4net.config文件,将下面的配置复制进去
"1.0" encoding="utf-8"?>"log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> "true" targetFramework="4.5.2" /> "4.5.2" /> "ErrorAppender" type="log4net.Appender.RollingFileAppender"> "Content\\LogError"/> "true"/> "Date"/> "yyyy\\yyyyMM\\yyyyMMdd'.txt'"/> "false"/> "MaxSizeRollBackups" value="100"/> "1GB" /> "log4net.Layout.PatternLayout"> "%n========== %n【日志级别】%-5level %n【记录时间】%date %n【线程编号】[%thread] %n【执行时间】[%r]毫秒 %n【出错文件】%F %n【出错行号】%L %n【出错的类】%logger 属性[%property{NDC}] %n【错误描述】%message %n【错误详情】%newline"/> "logerror"> "ERROR" /> ref ref="ErrorAppender" />
3.打开Properties中的Assemblyinfo.cs
将代码放进去, AssemblyInfo.cs主要用来设定生成的有关程序集的常规信息dll文件的一些参数
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
5.在Global.asax设置log4net
log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(Server.MapPath("/Log4net.config")));
6.log4netHelper的帮助类
public class Log4netHelper { #region ////// /// /// public static void ErrorLog(object msg) { log4net.ILog log = log4net.LogManager.GetLogger("logerror"); Task.Run(() => log.Error(msg)); //异步 // Task.Factory.StartNew(() =>log.Error(msg));// 这种异步也可以 //log.Error(msg); //这种也行跟你需要,性能越好,越强大,我还是使用异步方式 } /// /// /// /// public static void ErrorLog(Exception ex) { log4net.ILog log = log4net.LogManager.GetLogger("logerror"); Task.Run(() => log.Error(ex.Message.ToString() + "/r/n" + ex.Source.ToString() + "/r/n" + ex.TargetSite.ToString() + "/r/n" + ex.StackTrace.ToString())); } /// /// /// /// /// public static void ErrorLog(object msg, Exception ex) { log4net.ILog log = log4net.LogManager.GetLogger("logerror"); if (ex != null) { Task.Run(() => log.Error(msg, ex)); //异步 } else { Task.Run(() => log.Error(msg)); //异步 } } #endregion }
7.直接是调用帮助类,里面一个有三个方法,ErrorLog重载,根据自己的需要来调用