将异常写入Windows日志文件

39

我想捕获异常并将其记录在Windows日志文件中。如何打开并写入Windows日志?

5个回答

40
你可以使用System.Diagnostics.EventLog.WriteEntry函数向事件日志中写入条目。
System.Diagnostics.EventLog.WriteEntry("MyEventSource", exception.StackTrace,                  
                                       System.Diagnostics.EventLogEntryType.Warning);

要读取事件日志,您可以使用System.Diagnostics.EventLog.GetEventLogs函数。

//here's how you get the event logs
var eventLogs = System.Diagnostics.EventLog.GetEventLogs();

foreach(var eventLog in eventLogs)
{    
    //here's how you get the event log entries
    foreach(var logEntry in eventLog.Entries)
    {
        //do something with the entry
    }    
}

11

你也可以考虑使用Enterprise Library。虽然刚开始看起来有些复杂,但玩上一个或两个小时就会很值得了。配置存储在app.config中,因此您可以在不重新编译的情况下进行更改-当您在测试和生产服务器上都有相同的代码但有不同的配置时,这非常方便。您可以在不需要大量代码的情况下完成很多工作。

其中一个好处是,您可以定义异常策略,以使异常自动记录。 以下是您可能使用的一些代码(我正在使用EntLib 4.1):

    try
    {
        //This would be where your exception might be thrown.  I'm doing it on
        //purpose so you can see it work
        throw new ArgumentNullException("param1");
    }
    catch (Exception ex)
    {
        if (ExceptionPolicy.HandleException(ex, "ExPol1")) throw;
    }
在catch块中的代码行,将重新抛出异常,如果ExPol1定义它。 如果ExPol1配置为重新抛出,则ExceptionPolicy.HandleException将返回true。 如果没有,则返回false。
您可以在配置文件中定义其余部分。 XML看起来相当可怕(总是这样),但您可以使用Enterprise Library Configuration编辑器创建它。 我只是提供完整性。
在loggingConfiguration部分中,该文件定义
- 日志:滚动文本日志文件(您可以使用内置的Windows事件日志,SQL表,电子邮件,MSMQ和其他工具),以及 - 文本格式化程序,管理如何将参数写入日志(有时我会将其配置为将所有内容写入一行,有时会分散在许多行中), - 单个类别“General”。 - 特殊来源,捕获config / entlib中的任何错误并报告它们。 我强烈建议您这样做。
在exceptionHandling部分中,它定义了
- 单个策略:“ExPo1”,用于处理类型为ArgumentNullException的异常,并指定postHandlingAction为None(即不重新抛出)。 - 处理程序记录到上述定义的“General”类别中。
在此示例中,我没有这样做,但您也可以使用策略替换异常类型。
   <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        <section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </configSections>
      <loggingConfiguration name="Logging Application Block" tracingEnabled="true"
        defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
        <listeners>
          <add fileName="rolling.log" footer="" formatter="Text Formatter"
            header="" rollFileExistsBehavior="Overwrite" rollInterval="None"
            rollSizeKB="500" timeStampPattern="yyyy-MM-dd" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            name="Rolling Flat File Trace Listener" />
        </listeners>
        <formatters>
          <add template="Timestamp: {timestamp}; Message: {message}; Category: {category}; Priority: {priority}; EventId: {eventid}; Severity: {severity}; Title:{title}; Machine: {machine}; Application Domain: {appDomain}; Process Id: {processId}; Process Name: {processName}; Win32 Thread Id: {win32ThreadId}; Thread Name: {threadName}; &#xD;&#xA;     Extended Properties: {dictionary({key} - {value})}"
            type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
            name="Text Formatter" />
        </formatters>
        <categorySources>
          <add switchValue="All" name="General">
            <listeners>
              <add name="Rolling Flat File Trace Listener" />
            </listeners>
          </add>
        </categorySources>
        <specialSources>
          <allEvents switchValue="All" name="All Events" />
          <notProcessed switchValue="All" name="Unprocessed Category" />
          <errors switchValue="All" name="Logging Errors &amp; Warnings">
            <listeners>
              <add name="Rolling Flat File Trace Listener" />
            </listeners>
          </errors>
        </specialSources>
      </loggingConfiguration>
      <exceptionHandling>
        <exceptionPolicies>
          <add name="ExPol1">
            <exceptionTypes>
              <add type="System.ArgumentNullException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                postHandlingAction="None" name="ArgumentNullException">
                <exceptionHandlers>
                  <add logCategory="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling"
                    formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                    priority="0" useDefaultLogger="false" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                    name="Logging Handler" />
                </exceptionHandlers>
              </add>
            </exceptionTypes>
          </add>
        </exceptionPolicies>
      </exceptionHandling>
    </configuration>

7
不解释地将某事物减一分,这样做不太礼貌,我做错了什么吗? - serialhobbyist

7

Windows使用事件日志跟踪活动。您可以使用System.Diagnostics.Trace类:

var traceSwitch = new TraceSwitch("MySwitch", "");
var exception = new Exception("Exception message");

if (traceSwitch.TraceError)
{
    Trace.TraceError(exception);
}

您可以使用app.config指示记录器写入的位置:

<system.diagnostics>
    <switches>
        <add name="MySwitch" value="Verbose" />
    </switches>
    <trace autoflush="true">
        <listeners>
            <add name="EventLogger"
                 type="System.Diagnostics.EventLogTraceListener"
                 initializeData="NameOfYourApplication" />
        </listeners>
    </trace>
 </system.diagnostics>

6

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接