在MVC三层项目中如何使用Log4Net
2011 年 4 月 3 日
–前期准备(添加到队列中)
0-1在新建后的MVC项目中的【Models】中添加一个类,用于处理异常信息,并继承自HandleErrorAttribute
public class MyExceptionAttribute: HandleErrorAttribute { //创建队列集合 public static Queue ExceptionQueue = new Queue(); ////// 可以捕获异常数据 /// /// public override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); Exception ex = filterContext.Exception; //写到队列 //插入到队列里面 ExceptionQueue.Enqueue(ex); //跳转到错误页面 filterContext.HttpContext.Response.Redirect("/Error.html"); } }
0-2在FilterConfig文件中注册自己定义的异常处理过滤器
1.添加bll文件
2.在Web.Config中配置Log4Net
3.在Global.asax文件中的Application_Start方法中初始化log4net,不要加到页面的Load。
4.在Application_Start写以下代码,用来添加到队列
//【开启一个线程,扫描异常信息队列】 //拿到文件夹的物理路径 string filePath = Server.MapPath("/Log/"); //开启线程,使用线程池 ThreadPool.QueueUserWorkItem((a) => { //线程一直在执行 while (true) { //判断队列中有数据,Count>0表示有数据 if (MyExceptionAttribute.ExceptionQueue.Count > 0) { //取出数据 Exception ex = MyExceptionAttribute.ExceptionQueue.Dequeue(); //判断是否真正拿到数据 if (ex != null) { //【将异常信息写到日志文件中】 //根据年月日 来命名日志文件 //string fileName = DateTime.Now.ToString("yyyy-MM-dd"); //File.AppendAllText(filePath + fileName + ".txt", ex.ToString(),System.Text.Encoding.UTF8); //【使用log4net】 ILog logger = LogManager.GetLogger("errorMsg"); //将异常信息写入到log4net中 logger.Error(ex.ToString()); } else { //如果队列中没有数据,让线程休息3秒钟 Thread.Sleep(3000); } } else { //如果队列中没有数据,让线程休息3秒钟 Thread.Sleep(3000); } } }, filePath); }