首页 > 代码库 > 分布式日志1 用c#的队列写日志
分布式日志1 用c#的队列写日志
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace 分布式日志{ public class MyExceptionFilter : HandleErrorAttribute { public static Queue<Exception> listQueue = new Queue<Exception>(); public override void OnException(ExceptionContext filterContext) { if (filterContext.Exception!=null) { listQueue.Enqueue(filterContext.Exception); filterContext.HttpContext.Response.Redirect("/error.html"); } base.OnException(filterContext); } }}
using System.Web;using System.Web.Mvc;namespace 分布式日志{ public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { //filters.Add(new HandleErrorAttribute()); filters.Add(new MyExceptionFilter()); } }}
using System;using System.Collections.Generic;using System.Linq;using System.Threading;using System.Web;using System.Web.Mvc;using System.Web.Optimization;using System.Web.Routing;namespace 分布式日志{ public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //通过线程池开启一个线程,然后不停的从队列中读取数据 string strRoot = Server.MapPath("/Log/"); string strPath = strRoot + DateTime.Now.ToString("yyyy-MM-dd").ToString()+".txt"; ThreadPool.QueueUserWorkItem(i => { while (true) { try { if (MyExceptionFilter.listQueue.Count > 0) { Exception ex = MyExceptionFilter.listQueue.Dequeue(); if (ex != null) { System.IO.File.AppendAllText( strPath,DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ex.ToString() + Environment.NewLine,System.Text.Encoding.UTF8); } else { Thread.Sleep(30); } } else { Thread.Sleep(30);//避免cpu空转 } } catch(Exception ex) { MyExceptionFilter.listQueue.Enqueue(ex); } } }, strPath); } }}
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace 分布式日志.Controllers{ public class TestController : Controller { // // GET: /Test/ public ActionResult Index() { int aa = Convert.ToInt32("sss"); return View(); } }}
分布式日志1 用c#的队列写日志
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。