使用redis将日志记录到日志服务器

需求


代码实现

在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服务器的压力。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值