Logging Exceptions

本文介绍如何在ASP.NET页面中使用事件日志记录错误信息,并提供了代码示例。通过自定义日志类和注册事件源,可以高效地记录异常情况。

 

 Writing to the Event Log 

You can interact with event logs in  an ASP.NET page by using the cl asses in the System.Diagnostics 
namespace. First, import the namespace at  the beginning of your code-behind file: 
using System.Diagnostics; 
The following example rewrites the simple ErrorTest page to use event logging: 
public partial class ErrorTestLog : Page 

    protected void cmdCompute_Click(Object sender, EventArgs e) 
    { 
        try 
        { 
            decimal a, b, result; 
            a = Decimal.Parse(txtA.Text); 
            b = Decimal.Parse(txtB.Text); 
            result = a / b; 
            lblResult.Text = result.ToString(); 
            lblResult.ForeColor = System.Drawing.Color.Black; 
        } 
        catch (Exception err) 
        { 
            lblResult.Text = "<b>Message:</b> " + err.Message + "<br /><br />"
            lblResult.Text += "<b>Source:</b> " + err.Source + "<br /><br />"
            lblResult.Text += "<b>Stack Trace:</b> " + err.StackTrace; 
            lblResult.ForeColor = System.Drawing.Color.Red; 
 
            // Write the information to the event log. 
            EventLog log = new EventLog(); 
            log.Source = "DivisionPage"
            log.WriteEntry(err.Message, EventLogEntryType.Error); 
        } 
    } 
}

 

Custom Log

// Register the event source if needed. 
if (!EventLog.SourceExists("ProseTech")) 

    // This registers the event source and creates the custom log, 
    
// if needed. 
    EventLog.CreateEventSource("DivideByZeroApp""ProseTech"); 

 
// Open the log. If the log doesn't exist, 
// it will be created automatically. 
EventLog log = new EventLog("ProseTech"); 
log.Source = "DivideByZeroApp"
log.WriteEntry(err.Message, EventLogEntryType.Error); 

 

A Custom Logging Class

Here’s an example of a class named MyLogger that handles the event logging details: 
public class MyLogger 

    public void LogError(string pageInError, Exception err) 
    { 
        RegisterLog(); 
 
        EventLog log = new EventLog("ProseTech"); 
        log.Source = pageInError; 
        log.WriteEntry(err.Message, EventLogEntryType.Error); 
    } 
 
    private void RegisterLog() 
    { 
        // Register the event source if needed. 
        if (!EventLog.SourceExists("ProseTech")) 
        { 
           EventLog.CreateEventSource("DivideByZeroApp""ProseTech"); 
        } 
    } 
Once you have a class in the App_Code folder, it’s ea sy to use it anywhere in your website. Here’s 
how you might use the MyLogger class in a web page to log an exception: 
try 

    // Risky code goes here. 

catch (Exception err) 

    // Log the error using the logging class. 
    MyLogger logger = new MyLogger(); 
    logger.LogError(Request.Path, err); 
 
    // Now handle the error as appropriate for this page. 
    lblResult.Text = "Sorry. An error occurred."

 

 

 

Retrieving Log Information  


Here’s the web page code you’ll need:

public partial class EventReviewPage : System.Web.UI.Page
{
  protected void cmdGet_Click(Object sender, EventArgs e)
  {
     lblResult.Text = "";
     // Check if the log exists.
     if (!EventLog.Exists(txtLog.Text))
     {
        lblResult.Text = "The event log " + txtLog.Text ;
        lblResult.Text += " doesn't exist.";
     }
     else
     {
        EventLog log = new EventLog(txtLog.Text);
        foreach (EventLogEntry entry in log.Entries)
        {
          // Write the event entries to the page.
          if (chkAll.Checked ||
            entry.Source == txtSource.Text)
          {
             lblResult.Text += "<b>Entry Type:</b> ";
             lblResult.Text += entry.EntryType.ToString();
             lblResult.Text += "<br /><b>Message:</b> ";
             lblResult.Text += entry.Message;
             lblResult.Text += "<br /><b>Time Generated:</b> ";
             lblResult.Text += entry.TimeGenerated;
             lblResult.Text += "<br /><br />";
          }
        }
     }
  }
  protected void chkAll_CheckedChanged(Object sender,
    EventArgs e)
  {
     // The chkAll control has AutoPostback = true.
     if (chkAll.Checked)
     {
        txtSource.Text = "";
        txtSource.Enabled = false;
     }
     else
     {
        txtSource.Enabled = true;
     }
  }
}


Here’s the more efficient way (using StringBuilder)  you could write the string processing code : 
// For maximum performance, join all the event 
// information into one large string using the 
// StringBuilder. 
System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
 
EventLog log = new EventLog(txtLog.Text); 
foreach (EventLogEntry entry in log.Entries) 

    // Write the event entries to the StringBuilder. 
    if (chkAll.Checked || 
      entry.Source == txtSource.Text) 
    { 
        sb.Append("<b>Entry Type:</b> "); 
        sb.Append(entry.EntryType.ToString()); 
        sb.Append("<br /><b>Message:</b> "); 
        sb.Append(entry.Message); 
        sb.Append("<br /><b>Time Generated:</b> "); 
        sb.Append(entry.TimeGenerated); 
        sb.Append("<br /><br />"); 
    } 
    // Copy the complete text to the web page. 
    lblResult.Text = sb.ToString(); 

 

转载于:https://www.cnblogs.com/JasonBie/archive/2012/04/11/2442481.html

### 正确抛出和处理 `connexion.exceptions.ProblemException` 异常 在使用 Connexion 框架开发 RESTful API 时,为了保持响应的一致性和标准化错误处理机制,推荐使用 `ProblemException` 来表示应用程序中的问题。这不仅有助于客户端理解发生了什么情况,还能够简化服务器端的异常管理逻辑。 当需要手动触发一个 HTTP 错误状态码给调用者的时候,可以创建并抛出 `ProblemException` 实例[^1]: ```python from connexion.exceptions import ProblemException def create_problem_exception(): raise ProblemException( title="Resource Not Found", detail="The requested resource could not be found.", status=404, type="about:blank" ) ``` 对于捕获以及优雅地返回这些自定义异常至客户端请求,则依赖于框架内置的支持特性来完成。只要确保所使用的版本支持自动转换此类型的异常到符合 RFC7807 的 JSON 响应格式即可[^2]。 此外,在应用层面上也可以通过配置全局错误处理器进一步增强灵活性与可维护性。例如设置 Flask 应用程序级别的错误处理器以统一方式处理所有未被捕获的 `ProblemException`: ```python import logging from flask import jsonify, current_app as app from werkzeug.exceptions import default_exceptions from connexion.exceptions import ProblemException @app.errorhandler(ProblemException) def handle_invalid_usage(error): response = jsonify({ "type": error.type, "title": error.title, "status": error.status, "detail": error.detail, }) response.status_code = error.status or 500 return response ``` 上述代码片段展示了如何注册一个专门用于捕捉 `ProblemException` 的错误处理器,并将其序列化成 JSON 格式的回复发送回给客户端[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值