2009-07-26 14 views

Respuesta

33

Puede usar la función System.Diagnostics.EventLog.WriteEntry para escribir entradas en el registro de eventos.

System.Diagnostics.EventLog.WriteEntry("MyEventSource", exception.StackTrace,     
             System.Diagnostics.EventLogEntryType.Warning); 

Para leer registros de eventos se puede utilizar la función de 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 
    }  
} 
6

Windows usa el registro de eventos para rastrear la actividad. Puede utilizar la clase System.Diagnostics.Trace:

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

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

Y puede utilizar app.config para instruir el registrador de dónde escribir:

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

También puede considerar el uso de la Enterprise Library. Parece complicado para empezar, pero una o dos horas de juego dará sus frutos. La configuración se almacena en app.config para que pueda cambiarla sin volver a compilarla. Esto puede ser muy útil cuando tiene el mismo código en servidores de prueba y en vivo con configuraciones diferentes. Puedes hacer bastante sin cargas de código.

Una cosa buena es que puede definir las políticas de excepciones para que las excepciones se registren automáticamente. Aquí hay un código que podría utilizar (estoy usando 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; 
    } 

La línea en el bloque catch será volver a lanzar la excepción si el ExPol1 define. Si ExPol1 está configurado para volver a lanzar, entonces ExceptionPolicy.HandleException devolverá verdadero. Si no, devuelve falso.

Define el resto en config. El XML se ve bastante horrible (no siempre), pero se crea con el editor de configuración de la biblioteca de la empresa. Solo estoy proveyéndolo para que esté completo.

En la sección loggingConfiguration, este archivo define

  • el registro: un archivo de registro de texto de trabajo (se puede utilizar el construido en los registros de eventos de Windows, tablas SQL, correo electrónico, MSMQ y otros), con
  • un formateador de texto que gobierna cómo los parámetros se escriben en el registro (a veces puedo configurar esto para escribir todo para una línea, otras veces se extienden a través de muchos),
  • una sola categoría "general"
  • una fuente especial que atrapa cualquier error en config/entlib y repo ellos también. Te recomiendo encarecidamente que hagas esto.

En la sección ExceptionHandling, define

  • una única política: "ExPo1", que maneja escriba ArgumentNullExceptions y especifica la postHandlingAction de Ninguno (es decir, no volver a lanzar).
  • un controlador que registra a la categoría general (definido anteriormente)

que no lo haga en este ejemplo, pero también se puede reemplazar una excepción con un tipo diferente utilizando una política.

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

¿No es un poco desagradable a -1 algo sin explicar? ¿Qué hice mal? – serialhobbyist

Cuestiones relacionadas