65.9K
CodeProject 正在变化。 阅读更多。
Home

自定义错误日志记录

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2013 年 10 月 11 日

CPOL

4分钟阅读

viewsIcon

8513

本文介绍了一种记录和邮寄任何网页错误的方法。它记录以下详细信息:引发错误的控件页面

本文介绍了一种记录和邮寄任何网页错误的方法。

它记录以下详细信息:

  • 引发错误的控件
  • 控制错误的页面
  • 错误描述
  • 跟踪消息
  • 服务器和客户端详细信息

日志在根目录下的 log 文件夹中创建。

 
源代码在类文件 errorHandler.cs 中提供



using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;
using System.IO;


/// <summary>
/// 此类旨在记录 myweb 门户中的运行时错误并发送相关邮件。
/// 运行时错误。
///
/// 开发者:yeotumitsu@sify.com
/// 日期:2008-04-24
/// 修改日期:2008-04-25
/// </summary>

public enum MessageType // 枚举用于提供要执行的操作
{
    EventLog,
    SendMail,
    MailAndEventLog
}


public class errorHandler
{
    public MessageType MsgType
    {
        get
        {
            return this.MT;
        }
        set
        {
            this.MT = value;
        }
    }

    public MessageType MT = new MessageType();
  
    public string EmailReciever = "";
    public string LogName = "";
    public string MailServer = "";
    public string MailSubject = "错误报告 " + HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
    

    public errorHandler() // 设置字段的默认值
    {
        this.MailServer = ConfigurationSettings.AppSettings["MailServer"];
        this.EmailReciever = ConfigurationSettings.AppSettings["MailReciever"];
        this.LogName = ConfigurationSettings.AppSettings["LogName"];
    }

    /// <summary>
    /// 函数 errorHandler 重载。
    /// 如果用户提供,则设置默认值。
    /// </summary>
    /// <param name="_mailserver"> SMTP 服务器 IP </param>
    /// <param name="_mailreciever"> 应该接收错误邮件的人的电子邮件 ID </param>
    /// <param name="_logname"> 错误日志的名称 </param>
  
    public errorHandler(string _mailserver, string _mailreciever, string _logname)
    {
        this.MailServer        = _mailserver;
        this.EmailReciever    = _mailreciever;
        this.LogName        = _logname;
    }

    /// <summary>
    /// 调用 raiseError 以选择要执行的操作
    /// </summary>
    /// <param name="_message"> 任何消息 </param>
    /// <param name="ex"> 异常  </param>
    public void RaiseError(string _message, Exception ex)
    {
       switch (this.MT)
        {
            case MessageType.EventLog
                SaveToEventLog(_message, ex);
                break;
            case MessageType.SendMail
                sendErrorMail(_message);
                break;
            case MessageType.MailAndEventLog
                SaveToEventLog(_message, ex);
                sendErrorMail(_message);
                break;
            default
                break;
        }
    }

    /// <summary>
    /// 向指定接收邮件的人发送邮件
    /// </summary>
    /// <param name="_message"> 要发送的消息 </param>
    /// <returns> </returns>
    public int sendErrorMail(string _message)
    {
        MailMessage errorMessage = new MailMessage();
        errorMessage.To.Add(new MailAddress(this.EmailReciever));
        errorMessage.Subject = this.MailSubject;
        errorMessage.IsBodyHtml = true;
        errorMessage.Priority = MailPriority.High;
        errorMessage.Body = _message + " 请查看日志以获取更多信息。";
        SmtpClient clientSmtp = new SmtpClient();
        try
        {
            clientSmtp.Send(errorMessage);
        }
        catch
        {
            return 0;
        }
        return 1;
    }


    /// <summary>
    /// 格式化并记录错误
    /// </summary>
    /// <param name="_message"> 任何消息 </param>
    /// <param name="ex"> 异常  </param>
  
    private void SaveToEventLog(string _message, Exception ex)
    {
        try
        {
            string strPhysicalApplicationPath = HttpContext.Current.Request.PhysicalApplicationPath;
            string strFileName = strPhysicalApplicationPath + "Logs\\" + LogName + DateTime.Now.ToString("ddMMMyyyy") + ".txt";
            string strBody = string.Empty;
            FileInfo fInfo = new FileInfo(strFileName);

            strBody = _message + Environment.NewLine + Environment.NewLine;
            strBody +=  "服务器地址 :: " + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + Environment.NewLine;
            strBody += "用户地址   :: " + HttpContext.Current.Request.ServerVariables["REMOTE_HOST"] + Environment.NewLine;
            strBody += "脚本名称    :: " + HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"] + Environment.NewLine;
            strBody += "查询数据     :: " + HttpContext.Current.Request.Url.Query + Environment.NewLine;
            strBody += "发生时间     :: " + DateTime.Now + Environment.NewLine + Environment.NewLine;
            strBody += "################################## -- 错误开始  -- #################################" + Environment.NewLine;
            strBody += ex.StackTrace + Environment.NewLine;
            strBody += "################################### -- 错误结束 -- ###################################" + Environment.NewLine + Environment.NewLine;
            strBody += HttpContext.Current.Request.ServerVariables["ALL_HTTP"] + Environment.NewLine;

            DirectoryInfo dInfo = new DirectoryInfo(strPhysicalApplicationPath + "Logs\\");
            if (!dInfo.Exists)
            {
                dInfo.Create();
            }

            if (fInfo.Exists)
            {
                FileStream fStream = new FileStream(strFileName, FileMode.Append, FileAccess.Write);
                StreamWriter sWriter = new StreamWriter(fStream);
                sWriter.WriteLine(strBody);
                sWriter.Close();
            }
            else
            {
                FileStream fStream = new FileStream(strFileName, FileMode.Create, FileAccess.Write);
                StreamWriter sWriter = new StreamWriter(fStream);
                sWriter.WriteLine(strBody);
                sWriter.Close();
            }
        }
        catch (Exception e)
        {
            sendErrorMail(e.Message);
        }
    }
}


Web 配置设置 -  

 <appSettings>
        <add key="MailServer" value="127.0.0.1"/>
        <add key="MailReciever" value="you@yourSite.com"/>
        <add key="LogName" value="EmpostErrLog"/>
    </appSettings>
    <system.net>
        <mailSettings>
            <smtp from="admin@yourSite.com">
                <network host="127.0.0.1"/>
            </smtp>
        </mailSettings>
    </system.net>

 


调用方法 -

 catch(Exception ex)
        {
            string strMsg = "日期 : " + DateTime.Now.ToString("dd/MMM/yyyy HH:mm:ss") + "  错误 : " + ex.Message + " 控件 : " + ((Control)sender).ClientID.ToString() + " 页面 :  " + Page;
            errorHandler objErrorHandler = new errorHandler();
            objErrorHandler.MsgType = MessageType.MailAndEventLog;
            objErrorHandler.RaiseError(strMsg,ex);
        }

 

 


希望能有所帮助。

 

© . All rights reserved.