write registro puede permisos guardar escribir error crear clave cambios acceso c# windows logging event-log

c# - puede - Escribir excepciones al archivo de registro de Windows



no se puede guardar cambios a permisos (5)

Aquí está la respuesta simple al escribir en el registro de eventos: http://support.microsoft.com/kb/307024

Una mejor respuesta es usar algo como log4net , que se encargará de eso por ti.

Me gustaría detectar mis excepciones y registrarlas en el archivo de registro de Windows. ¿Cómo hago para abrir y escribir en el registro de Windows?



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 los registros de eventos, puede usar la función 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 } }


También puede considerar el uso de 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 políticas de excepción para que las excepciones se registren automáticamente. Aquí hay un código que puede usar (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 volverá a lanzar la excepción SI el ExPol1 lo define. Si ExPol1 está configurado para volver a lanzar, entonces ExceptionPolicy.HandleException devolverá verdadero. Si no, devuelve falso.

Usted 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 continuo (puede usar los registros de eventos integrados de Windows, tablas sql, correo electrónico, msmq y otros), con
  • un formateador de texto que rige cómo se escriben los parámetros en el registro (a veces configuro esto para escribir todo en una línea, otras veces repartidas entre muchas),
  • una sola categoría "General"
  • una Fuente especial que atrapa cualquier error en la configuración / intlib y los informa también. Te recomiendo encarecidamente que hagas esto.

En la sección exceptionHandling, define

  • una sola política: "ExPo1", que maneja el tipo ArgumentNullExceptions y especifica la PostHandlingAction de None (es decir, no volver a lanzar).
  • un controlador que inicia sesión en la categoría General (definida anteriormente)

No lo hago en este ejemplo, pero también puede reemplazar una excepción por 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>


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

var traceSwitch = new TraceSwitch("MySwitch", ""); var exception = new Exception("Exception message"); if (traceSwitch.TraceError) { Trace.TraceError(exception); }

Y puede usar app.config para indicar al registrador 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>