標籤:style blog http color os io 檔案 資料
attribute:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using ServiceStack.Redis;namespace RedisMvcApp.Models{ public class MyExecptionAttribute : HandleErrorAttribute { //public static Queue<Exception> ExceptionQueue = new Queue<Exception>();//建立隊列. public static IRedisClientsManager clientManager = new PooledRedisClientManager(new string[]{"127.0.0.1:6379"}); public static IRedisClient redisClent = clientManager.GetClient(); public override void OnException(ExceptionContext filterContext) { //將異常資訊入隊. //ExceptionQueue.Enqueue(filterContext.Exception);//將異常資訊入隊. redisClent.EnqueueItemOnList("errorException", filterContext.Exception.ToString());//將異常資訊儲存到Redis隊列中了。 filterContext.HttpContext.Response.Redirect("/error.html"); base.OnException(filterContext); } }}
gobal
using log4net;using RedisMvcApp.Models;using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using System.Threading;using System.Web;using System.Web.Http;using System.Web.Mvc;using System.Web.Optimization;using System.Web.Routing;namespace RedisMvcApp{ // 注意: 有關啟用 IIS6 或 IIS7 傳統模式的說明, // 請訪問 http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { log4net.Config.XmlConfigurator.Configure();//擷取Log4Net配置資訊(配置資訊定義在Web.config檔案中) AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //通過線程開啟一個線程,然後不停的從隊列中或資料 string filePath = Server.MapPath("/Log/"); ThreadPool.QueueUserWorkItem(o => { while (true) { try { // if (MyExecptionAttribute.ExceptionQueue.Count > 0) if (MyExecptionAttribute.redisClent.GetListCount("errorException") > 0) { // Exception ex= MyExecptionAttribute.ExceptionQueue.Dequeue();//從隊列中拿出資料 string errorMsg = MyExecptionAttribute.redisClent.DequeueItemFromList("errorException");//從Redis隊列中取出異常資料 //if (ex != null) if(!string.IsNullOrEmpty(errorMsg)) { //構建成一個完整的路徑 // string fileName = filePath + DateTime.Now.ToString("yyyy-MM-dd").ToString() + ".txt"; //string execptionMsg = ex.ToString(); // File.AppendAllText(fileName, errorMsg, Encoding.Default);//將異常寫到檔案中。 ILog logger = LogManager.GetLogger("czbkError"); logger.Error(errorMsg);//將異常資訊寫到Log4Net中. } else { Thread.Sleep(30); } } else { Thread.Sleep(30);//避免了CPU空轉。 } } catch (Exception ex) { //MyExecptionAttribute.ExceptionQueue.Enqueue(ex); MyExecptionAttribute.redisClent.EnqueueItemOnList("errorException", ex.ToString()); } } }, filePath); } }}
log放在 app_start裡面 可以防止被訪問