编写Windows日志文件的例外

Gol*_*old 34 c# windows logging event-log

我想捕获我的异常并将它们记录在Windows日志文件中.如何打开和写入Windows日志?

Rei*_*ica 35

您可以使用System.Diagnostics.EventLog.WriteEntry函数将条目写入事件日志.

System.Diagnostics.EventLog.WriteEntry("MyEventSource", exception.StackTrace,                  
                                       System.Diagnostics.EventLogEntryType.Warning);
Run Code Online (Sandbox Code Playgroud)

要读取事件日志,可以使用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
    }    
}
Run Code Online (Sandbox Code Playgroud)


ser*_*ist 10

您还可以考虑使用企业库.一开始看起来很复杂,但一两个小时的比赛将会有所回报.配置存储在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;
    }
Run Code Online (Sandbox Code Playgroud)

如果ExPol1定义了异常,则catch块中的行将重新抛出异常.如果ExPol1配置为rethrow,则ExceptionPolicy.HandleException将返回true.如果不是,则返回false.

您可以在config中定义其余部分.XML看起来非常糟糕(并非总是如此),但您可以使用Enterprise Library Configuration编辑器创建它.我只是提供完整性.

在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>
Run Code Online (Sandbox Code Playgroud)

  • 在没有解释的情况下-1不是有点粗鲁吗?我做错了什么? (7认同)

Dar*_*rov 6

Windows使用事件日志来跟踪活动.你可以使用这个System.Diagnostics.Trace类:

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

if (traceSwitch.TraceError)
{
    Trace.TraceError(exception);
}
Run Code Online (Sandbox Code Playgroud)

您可以使用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>
Run Code Online (Sandbox Code Playgroud)


Jon*_*way 5

以下是写入事件日志的简单答案:http://support.microsoft.com/kb/307024

更好的答案是使用像log4net这样的东西,它会为你处理.