zoukankan      html  css  js  c++  java
  • C#开发中,添加错误日志功能,并自定义错误页面

    参考地址:https://blog.csdn.net/yiyelanxin/article/details/72778972

    在Global.asax中,添加Application_Error如下代码.

    protected void Application_Error()
    {
    var e = Server.GetLastError();
    var httpError = e as HttpException;

    //错误日志
    //在出现未处理的错误时运行的代码
    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("错误编码:" + httpError.GetHttpCode());
    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();
    }
    }

    /////自定义错误页面

    //默认500
    if (httpError == null)
    {
    Server.Transfer("~/Errors/500.html");
    //Response.WriteFile("~/Errors/500.html");
    Server.ClearError();
    }
    else
    {
    var errorCode = httpError.GetHttpCode();
    if (errorCode == 404)
    {
    Server.Transfer("~/Errors/404.html");
    Server.ClearError();
    }
    }
    }

  • 相关阅读:
    分享 35 套精美的 PSD 图标素材
    HTML 5 标签、属性、事件及浏览器兼容性速查表
    推荐21款最佳 HTML 5 网页游戏
    二分查找
    双指针合并两个排序数组
    关于explorer.exe文件或目录已损坏的问题
    一文弄懂数组的和
    云效DevOps实践如何基于云效实现测试自动化集成和分析
    五福背后的 Web 3D 引擎 Oasis Engine 正式开源
    Delta Lake在Soul的应用实践
  • 原文地址:https://www.cnblogs.com/kingsmart/p/13426161.html
Copyright © 2011-2022 走看看