using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using ServiceStack.Redis;

namespace 分布式日志
{
    public class MyExceptionFilter : HandleErrorAttribute
    {
        #region 用c#的队列
        //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);
        //}
        #endregion

        #region 用redis的队列
        public static IRedisClientsManager clientsManager=new PooledRedisClientManager(new string[]{"127.0.0.1:6379"});
        public static IRedisClient redisClient=clientsManager.GetClient();
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.Exception != null)
            {
                redisClient.EnqueueItemOnList("exception",filterContext.Exception.ToString());//入队
                filterContext.HttpContext.Response.Redirect("/error.html");
            }
            base.OnException(filterContext);
        }
        #endregion
    }
}
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)
                {
                    #region c# 队列
                    //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);
                    //}
                    #endregion

                    #region redis 队列
                    string strKey = "exception";
                    try
                    {
                        )
                        {
                            string strMsg = MyExceptionFilter.redisClient.DequeueItemFromList(strKey);
                            if (!string.IsNullOrEmpty(strMsg))
                            {
                                System.IO.File.AppendAllText(strPath, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + strMsg + Environment.NewLine, System.Text.Encoding.UTF8);
                            }
                            else
                            {
                                Thread.Sleep();
                            }
                        }
                        else
                        {
                            Thread.Sleep();//避免cpu空转
                        }
                    }
                    catch (Exception ex)
                    {
                        MyExceptionFilter.redisClient.EnqueueItemOnList(strKey, ex.ToString());
                    }
                    #endregion
                }
            }, strPath);
        }
    }
}
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());
        }
    }
}

分布式日志2 用redis的队列写日志的更多相关文章

  1. 分布式日志1 用c#的队列写日志

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  2. 重复造轮子,编写一个轻量级的异步写日志的实用工具类(LogAsyncWriter)

    一说到写日志,大家可能推荐一堆的开源日志框架,如:Log4Net.NLog,这些日志框架确实也不错,比较强大也比较灵活,但也正因为又强大又灵活,导致我们使用他们时需要引用一些DLL,同时还要学习各种用 ...

  3. python 14篇 写日志

    import sys from loguru import logger # 日志级别: debug 调试信息打印日志比较详细,级别最低 # info 正常的提示信息,级别较低 # waring 警告 ...

  4. Redis 自定义 RedisAppender 插件, 实现日志缓冲队列,集中日志输出.

    因为某些异步日志设置了即使队列满了,也不可丢弃,在并发高的时候,导致请求方法同步执行,响应变慢. 编写这个玩意,除了集中日志输出以外,还希望在高并发的时间点有缓冲作用. 之前用Kafka实现了一次入队 ...

  5. 利用StackExchange.Redis和Log4Net构建日志队列

    简介:本文是一个简单的demo用于展示利用StackExchange.Redis和Log4Net构建日志队列,为高并发日志处理提供一些思路. 0.先下载安装Redis服务,然后再服务列表里启动服务(R ...

  6. java-spring基于redis单机版(redisTemplate)实现的分布式锁+redis消息队列,可用于秒杀,定时器,高并发,抢购

    此教程不涉及整合spring整合redis,可另行查阅资料教程. 代码: RedisLock package com.cashloan.analytics.utils; import org.slf4 ...

  7. c# 多线程使用队列顺序写日志的类 (需要再优化)

    using System; using System.Collections.Generic; using System.Threading; public class LogManager { // ...

  8. Docker部署Django项目+Nginx+Fluend日志收集 和redis、memcached、RabbitMQ、Celery

    前言 一.docker 1.docker是什么? Docker的英文本意是“搬运工”,Docker搬运的是集装箱(Container)可以成为容器,我可以把写的Django的WEB应用以及Python ...

  9. ELK(+Redis)-开源实时日志分析平台

    ################################################################################################### ...

随机推荐

  1. Junit4常用注解

    Junit4注解 JUnit4的测试类不用再继承TestCase类了.使用注解会方便很多. @Before:初始化方法@After:释放资源@Test:测试方法,在这里可以测试期望异常和超时时间@Ig ...

  2. Yii里文件上传的操作方法(图片修改,在详情上展示,批量上传待续...)

    $model->img= UploadedFile::getInstance($model,'img');if ($model->validate()) {//$model->img ...

  3. [家里蹲大学数学杂志]第269期韩青编《A Basic Course in Partial Differential Equations》 前五章习题解答

    1.Introduction 2.First-order Differential Equations Exercise2.1. Find solutons of the following inti ...

  4. 透明(颜色)渐变背景(颜色透明背景),兼容IE8

    filter: progid:DXImageTransform.Microsoft.gradient (GradientType=0, startColorstr=#00000000, endColo ...

  5. 47. Largest Rectangle in Histogram && Maximal Rectangle

    Largest Rectangle in Histogram Given n non-negative integers representing the histogram's bar height ...

  6. Runloop基础知识

    *:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } ...

  7. JavaScript笔记:数据类型

    javascript中有5种基本数据类型:Undefined,Null,Boolean,Number和String,还有一种复杂的数据类型--Object.javascript不支持任何创建自定义类型 ...

  8. transition实现自定义tips淡入淡出效果

    transition实现动画的时候,只能实现指定属性的渐变,元素显隐要通过opacity来实现: 做了一个小的demo: <!doctype html> <html> < ...

  9. SQL笔记-第四章,数据的检索

    一.select的简单用法 1.简单的数据检索 SELECT * FROM T_Employee; 2.检索出需要的列 SELECT FNumber,FName,FAge FROM T_Employe ...

  10. Python变量作用域(一)

    在一个程序中使用变量名时,Python创建.改变或者查找变量名都是在所谓的命名空间中进行的.作用域指的就是命名空间. Python中的变量名在第一次赋值时已经创建,并且必须经过赋值后才能够使用.由于变 ...