2009-07-26 13 views

Répondre

33

Vous pouvez utiliser la fonction System.Diagnostics.EventLog.WriteEntry pour écrire des entrées dans le journal des événements.

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

Pour lire les journaux d'événements, vous pouvez utiliser la fonction 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 utilise l'activité de trace du journal des événements. Vous pouvez utiliser la classe System.Diagnostics.Trace:

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

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

Et vous pouvez utiliser app.config pour instruire l'enregistreur où écrire:

<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

Vous pouvez également envisager d'utiliser la Enterprise Library. Cela a l'air compliqué au début mais une heure ou deux de jeu sera payante. Config est stocké dans app.config afin que vous puissiez le modifier sans recompiler - cela peut être très utile lorsque vous avez le même code assis sur des serveurs test et live avec une configuration différente. Vous pouvez faire beaucoup de choses sans beaucoup de code.

Une bonne chose est que vous pouvez définir des politiques d'exception afin que les exceptions soient automatiquement consignées. Voici un code que vous pouvez utiliser (j'utilise 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 ligne dans le bloc catch relancera l'exception si le ExPol1 définit. Si ExPol1 est configuré pour être renvoyé, ExceptionPolicy.HandleException retournera true. Sinon, il renvoie false.

Vous définissez le reste dans la configuration. Le XML semble assez horrible (n'est-ce pas toujours le cas) mais vous le créez à l'aide de l'éditeur de configuration de la bibliothèque d'entreprise. Je fournis juste pour l'exhaustivité.

Dans la section loggingConfiguration, ce fichier définit

  • le journal: un fichier journal de texte évolutif (vous pouvez utiliser les journaux d'événements intégrés dans des fenêtres, des tables SQL, email, MSMQ et autres), avec
  • un formateur de texte qui régit la façon dont les paramètres sont écrits dans le journal (parfois configurer ceci pour écrire tout à une ligne, d'autres fois répartis sur un grand nombre),
  • une seule catégorie « général »
  • une source spéciale qui pièges des erreurs dans la config/entlib et repo les rts aussi. Je vous conseille fortement de le faire.

Dans la section ExceptionHandling, il définit

  • une politique unique: "ExPo1", qui gère les types ArgumentNullExceptions et spécifie le postHandlingAction de None (à savoir ne pas réémettre).
  • un gestionnaire qui se connecte à la catégorie générale (définie ci-dessus)

Je ne le fais pas dans cet exemple, mais vous pouvez également remplacer une exception avec un autre type à l'aide d'une politique.

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

est-il pas un peu grossier à -1 quelque chose sans expliquer? Qu'ai-je fait de mal? – serialhobbyist

Questions connexes