C#错误异常日志记录到文件

当我们将网站布署到线上之后,为了实时了解网站的运行情况,如是否有错误页面、网站运行速度、是否有攻击等。那么我们就很有必要为网站加上错误与异常记录到日志文件,这样就可以随时查看网站的线上运行情况,另有一个好处是当网站有运行错误页面时,根据错误日志我们可以快速到定位到错误行进行排查原因、解决问题,这个是对于运行在线上而不能调试的网站的一个非常有必要的功能。
具体实现方法:

在全局文件Global.asax.cs中添加Application_Error的方法。只要当程序有错误时程序就会自动执行该方法,从而记录到错误日志。

void Application_Error(object sender, EventArgs e)
{
    //在出现未处理的错误时运行的代码
    Exception ex = Server.GetLastError().GetBaseException();
    string errorTime = "异常时间:" + DateTime.Now.ToString();
    string errorAddress = "异常地址:" + Request.Url.ToString();
    string errorInfo = "异常信息:" + ex.Message;
    string errorSource = "错误源:" + ex.Source;
    string errorType = "运行类型:" + ex.GetType();
    string errorFunction = "异常函数:" + ex.TargetSite;
    string errorTrace = "堆栈信息:" + ex.StackTrace;
    Server.ClearError();
    System.IO.StreamWriter writer = null;
    try
    {
        lock (this)
        {
            //写入日志 
            string path = string.Empty;
            path = Server.MapPath("~/ErrorLogs/");
            //不存在则创建错误日志文件夹
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path +=string.Format(@"\{0}.txt", DateTime.Now.ToString("yyyy-MM-dd"));

            writer = !File.Exists(path) ? File.CreateText(path) : File.AppendText(path); //判断文件是否存在,如果不存在则创建,存在则添加
            writer.WriteLine("用户IP:" + Request.UserHostAddress);
            writer.WriteLine(errorTime);
            writer.WriteLine(errorAddress);
            writer.WriteLine(errorInfo);
            writer.WriteLine(errorSource);
            writer.WriteLine(errorType);
            writer.WriteLine(errorFunction);
            writer.WriteLine(errorTrace);
writer.WriteLine("********************************************************************************************");
        }
    }
    finally
    {
        if (writer != null)
        {
            writer.Close();
        }
    }
    Server.Transfer("~/500webpage.aspx"); //跳转到显示友好错误的页面
}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值