Запись исключений к Windows Log File

Это прямо в предупреждении: ISO C запрещает преобразование указателя функции в тип указателя объекта, который включает в себя void*. Смотрите также этот вопрос .

Вы просто не можете напечатать адрес функции переносимым способом, поэтому вы не можете избавиться от предупреждения. Del>

Вы можете напечатать указатель на функцию, используя Предложение @R ..

34
задан Even Mien 17 September 2009 в 14:06
поделиться

4 ответа

Вы можете использовать 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
    }    
}
35
ответ дан 27 November 2019 в 16:53
поделиться

You can also consider using the Enterprise Library. It looks complicated to start with but an hour or two of playing will pay off. Config is stored in app.config so you can change it without recompiling - this can be really handy when you've got the same code sitting on test and live servers with different config. You can do quite a lot without loads of code.

One nice thing is that you can define Exception policies so that exceptions are automatically logged. Here's some code you might use (I'm using 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;
    }

The line in the catch block will rethrow the exception IF the ExPol1 defines it. If ExPol1 is configured for rethrow, then ExceptionPolicy.HandleException will return true. If not, it returns false.

You define the rest in config. The XML looks pretty horrible (doesn't it always) but you create this using the Enterprise Library Configuration editor. I'm just supplying it for completeness.

In the loggingConfiguration section, this file defines

  • the log: a rolling text log file (you can use the built in windows event logs, sql tables, email, msmq and others), with
  • a text formatter that governs how the parameters are written to the log (sometimes I configure this to write everything to one line, other times spread across many),
  • a single category "General"
  • a Special Source which traps any errors in the config/entlib and reports them as well. I strongly advise you to do this.

In the exceptionHandling section, it defines

  • a single policy: "ExPo1", which handles type ArgumentNullExceptions and specifies the postHandlingAction of None (i.e. don't rethrow).
  • a handler which logs to the General category (defined above)

I don't do it in this example, but you can also replace an exception with a different type using a policy.

   <?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>
10
ответ дан 27 November 2019 в 16:53
поделиться

Вот простой ответ на запись в журнал событий: http://support.microsoft.com/kb/307024

Лучшим ответом является использование чего-то вроде log4net , который сделает это за вас.

5
ответ дан 27 November 2019 в 16:53
поделиться

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
ответ дан 27 November 2019 в 16:53
поделиться
Другие вопросы по тегам:

Похожие вопросы: