学习PetShop 之 日志管理

本文介绍如何在ASP.NET应用程序中配置并使用事件日志记录功能,包括必要的Web.config设置、错误捕获与记录方法及创建事件源的过程。

需要加载:

using System.Diagnostics;

Web.config设置:


  <appSettings>

      ...............
    <add key="Event Log Source" value=".NET Pet Shop" />

     ...............

  </appSettings>

对全局的日志记录: 

在Global.asax文件里加入这样的函数:

//====================================================

  // Read in the name of the event log to use from web.config
  private static string LOG_SOURCE = ConfigurationSettings.AppSettings["Event Log Source"];

  protected void Application_Error(object sender, EventArgs e)
  {
   // If an exception is thrown in the application then log it to an event log
   Exception x = Server.GetLastError().GetBaseException();
   EventLog.WriteEntry(LOG_SOURCE, x.ToString(), EventLogEntryType.Error);
  }
//====================================================

创建日志:

   public static string EVENT_LOG_SOURCE = ConfigurationSettings.AppSettings["Event Log Source"];

  /// <summary>
  /// Creates the PetShop Event Source. This requires administrator privileges
  /// because it needs to write to the registry hive.
  /// </summary>
  /// <returns>If the event source was created successfully true is returned, otherwise false.</returns>
  public static bool CreateEventSource() {
   // make sure we have an event log
   if (!(EventLog.SourceExists(EVENT_LOG_SOURCE))) {
    try {
     EventLog.CreateEventSource(EVENT_LOG_SOURCE, "Application");
     return true;
    }
    catch (Exception) {
     return false;
    }
   }
   else { // the event source already exists
    return true;
   }
  }

 日志:

可以在windows的“事件查看器”里查看到该应用程序的日志事件。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值