簡體   English   中英

將異常寫入Windows日志文件

[英]Writing Exceptions to the Windows Log File

我想捕獲我的異常並將其記錄在Windows日志文件中。 如何打開和寫入Windows日志?

您可以使用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
    }    
}

您也可以考慮使用企業庫 開始時看起來很復雜,但是一兩個小時的演奏會有所回報。 Config存儲在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;
    }

如果ExPol1定義了該異常,則catch塊中的行將重新引發異常。 如果將ExPol1配置為重新拋出,則ExceptionPolicy.HandleException將返回true。 如果不是,則返回false。

您在配置中定義其余部分。 XML看起來很可怕(並非總是如此),但是您可以使用企業庫配置編輯器創建XML。 我只是為了完整性而提供它。

在loggingConfiguration部分中,此文件定義

  • 日志:滾動文本日志文件(您可以使用內置的Windows事件日志,sql表,電子郵件,msmq等)
  • 一個文本格式化程序,用於控制如何將參數寫入日志(有時我將其配置為將所有內容寫入一行,而其他時間分散在許多行中),
  • 單一類別“常規”
  • 一個特殊源,可捕獲config / entlib中的任何錯誤並報告它們。 我強烈建議您這樣做。

在exceptionHandling部分中,它定義了

  • 單個策略:“ ExPo1”,該策略處理ArgumentNullExceptions類型並指定None的postHandlingAction(即不重新拋出)。
  • 登錄到“常規”類別(上面定義)的處理程序

在本示例中,我沒有這樣做,但是您也可以使用策略將異常替換為其他類型。

   <?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>

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>

這是寫入事件日志的簡單答案: http : //support.microsoft.com/kb/307024

更好的答案是使用log4net之類的東西,它將為您處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM