.Net捕获网站异常信息记录操作日志

  第一步:在Global.asax文件下的Application_Error()中写入操作日志

        /// <summary>
        /// 整个网站出现异常信息,都会执行此方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_Error(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Common.LogHelper.LogBasePath)) //文件的绝对物理路径
            {
                Common.LogHelper.LogBasePath = Request.MapPath("/Log");
            }
            //往错误消息的队列里面写一个错误消息
            Common.LogHelper.ExcpetionInfoQueue.Enqueue(Server.GetLastError().ToString());
            //整个网站出现了未捕获的异常,一般就是跳转到一个错误页面
            //提醒错误,然后隔几秒跳回首页
            Response.Redirect("/WebForm1.aspx");

        }

  第二步:日志操作文件类

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Text;
 5 using System.Threading;
 6 using System.Web;
 7 
 8 namespace Common
 9 {
10     /// <summary>
11     /// 日志文件操作类
12     /// </summary>
13     public class LogHelper
14     {
15         public static string LogBasePath; //物理绝对路径
16         public static Queue<string> ExcpetionInfoQueue = new Queue<string>(); //日志消息队列
17         static LogHelper()
18         {
19             ThreadPool.QueueUserWorkItem(o =>
20             {
21                 while (true)
22                 {
23                     lock (ExcpetionInfoQueue)
24                     {
25                         if (ExcpetionInfoQueue.Count > 0)
26                         {
27                             //写入错误消息
28                             string strFileName = DateTime.Now.ToString(@"yyyy-MM-dd") + ".txt";
29                             string absoluteFileName = Path.Combine(LogBasePath,strFileName);
30                             using (FileStream fs = new FileStream(absoluteFileName, FileMode.Append, FileAccess.Write))
31                             {
32                                 string strError = ExcpetionInfoQueue.Dequeue(); //错误消息
33                                 byte[] buffer = Encoding.Default.GetBytes(strError);
34                                 fs.Write(buffer, 0, buffer.Length);
35                             }
36                         }
37                     }
38                 }
39             });
40         }
41     }
42 }

  后续还会更新用log4Net记录报错日志消息

原文地址:https://www.cnblogs.com/chenyanbin/p/11180608.html