需求
代码实现
在web服务器上
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CZBK.BookShop.WebUi.Models
{
public class MyExceptionAttribute : HandleErrorAttribute
{
// public static Queue<Exception> ExceptionQueue = new Queue<Exception>();
public static IRedisClientsManager clientManager = new PooledRedisClientManager(new string[] { "日志服务器IP地址:6379" });
public static IRedisClient redisClent = clientManager.GetClient();
/// <summary>
/// 捕获异常信息
/// </summary>
/// <param name="filterContext"></param>
public override void OnException(ExceptionContext filterContext)
{
// ExceptionQueue.Enqueue(filterContext.Exception);//将异常信息写入到队列中。
redisClent.EnqueueItemOnList("errorMsg", filterContext.Exception.ToString());//将异常写到Redis队列中。
filterContext.HttpContext.Response.Redirect("/Error.html");
base.OnException(filterContext);
}
}
}
日志服务器上安装Redis服务,使用C#客户端API写一个处理程序,启动一个线程使其不停运行。
using log4net;
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
namespace CZBK.BookShop.RedisServer
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();//读取配置文件中关于Log4Net的配置信息.
IRedisClientsManager clientManager = new PooledRedisClientManager(new string[] { "127.0.0.1:6379" });
IRedisClient redisClent = clientManager.GetClient();
string filePath = HttpContext.Current.Server.MapPath("/Log/");
ThreadPool.QueueUserWorkItem(o =>
{
while (true)
{
// if(MyExceptionAttribute.ExceptionQueue.Count>0)//判断队列中是否有异常信息
if (redisClent.GetListCount("errorMsg") > 0)
{
// Exception ex = MyExceptionAttribute.ExceptionQueue.Dequeue();//出队
string errorMsg = redisClent.DequeueItemFromList("errorMsg");//将Redis队列中的数据获取.
// if (ex != null)
if (!string.IsNullOrEmpty(errorMsg))
{
//string fullDir = filePath + DateTime.Now.ToString("yyyyMMdd") + ".txt";
//File.AppendAllText(fullDir, ex.ToString());
ILog logger = LogManager.GetLogger("error");
logger.Error(errorMsg);
//logger.Error(ex.ToString());
}
else
{
Thread.Sleep(3000);
}
}
else
{
Thread.Sleep(3000);
}
}
}, filePath);
}
通过这种方式,所有的日志就都记录在了日志服务器中,这样就大大缓解了Web服务器的压力。