1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
| 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);
}
}
}
|