前言:由于现在日志非常重要,但是在哪里打写日志比较好呢,我选择的是在global中,把错误代码网上抛,而不是在底层写大量的try catch然后在catch中来写日志,每个catch中的写日志这样就会避免了很多重复代码。当然这是目前我们采取的一个方法,大家可以提出更好地方法来管理日志,下面我开始写代码
第一步:尽量抛弃项目中try catch。看下代码
PRivatevoidExceptionTestOne()
{inta =1;intb =0;intc = a/b;
}
上面代码会抛一个异常
第二步:如果项目中必须用try catch怎么办,因为有时候连接wcf的时候如果出现异常时候我们需要关闭连接避免堵塞,那么我们就采取抛异常的方法
privatevoidExceptionTestTwo()
{try{
List<Simple> simples =null;
simples.Add(newSimple() { Name ="发生异常"});
}catch(Exception ex)
{thrownewException("",ex);
}
}
第三步:我们新建一个global.asax 在application_Error中把异常信息加入队列中 如下
//创建一个静态的队列记录把异常都放在队列中privatestaticQueue<Exception> queue =newQueue<Exception>();protectedvoidApplication_Error(objectsender, EventArgs e)
{
Exception exp=Server.GetLastError();if(exp !=null) {
queue.Enqueue(exp);
}
Server.ClearError();
}
第四步:异常信息加入日志(这里为了简单就写入txt文本中了)
protectedvoidApplication_Start(objectsender, EventArgs e) {
ThreadPool.QueueUserWorkItem(a=>{while(true) {try{if(queue.Count >0) {
Exception ex=queue.Dequeue();
WriteLog(ex);
}else{
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(3));
}
}catch(Exception ex) {
WriteLog(ex);
} } }); }
privatevoidWriteLog(Exception ex)
{if(!File.Exists(@"E:\C#系列\ExceptionDealWith\ExceptionDealWith\Log.txt")) {
FileStream fs1=newFileStream(@"E:\C#系列\ExceptionDealWith\ExceptionDealWith\Log.txt", FileMode.Create, Fileaccess.Write);//创建写入文件StreamWriter sw =newStreamWriter(fs1);
sw.WriteLine(ex.Message);//开始写入值sw.Close();
fs1.Close();
}else{
StreamWriter sr= File.AppendText(@"E:\C#系列\ExceptionDealWith\ExceptionDealWith\Log.txt");
sr.WriteLine(ex.Message);
sr.Close();
}
}
当然接入错误信息你可以多定义几个比喻ip地址,堆栈信息错误等基本就是这么多了。这是基本思路。有日志了我就就可以根据时间,ip等进行查询日志日志信息
下载