2009-07-26 24 views

Trả lời

33

Bạn có thể sử dụng chức năng System.Diagnostics.EventLog.WriteEntry để ghi các mục nhập vào nhật ký sự kiện.

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

Để đọc nhật ký sự kiện, bạn có thể sử dụng chức năng 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 
    }  
} 
5

Dưới đây là câu trả lời đơn giản trên bằng văn bản cho các bản ghi sự kiện: http://support.microsoft.com/kb/307024

Một câu trả lời tốt hơn là sử dụng một cái gì đó giống như log4net, mà sẽ xử lý điều đó cho bạn.

6

Windows sử dụng Nhật ký sự kiện để theo dõi hoạt động. Bạn có thể sử dụng lớp System.Diagnostics.Trace:

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

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

Và bạn có thể sử dụng app.config để hướng dẫn các logger nơi để viết:

<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

Bạn cũng có thể xem xét sử dụng Enterprise Library. Nó có vẻ phức tạp để bắt đầu với nhưng một hoặc hai giờ chơi sẽ trả hết. Config được lưu trữ trong app.config để bạn có thể thay đổi nó mà không cần biên dịch lại - điều này có thể thực sự tiện dụng khi bạn có cùng mã đang ngồi trên máy chủ thử nghiệm và trực tiếp với cấu hình khác nhau. Bạn có thể làm khá nhiều mà không cần tải mã.

Một điều thú vị là bạn có thể xác định chính sách ngoại lệ để các ngoại lệ được tự động đăng nhập. Dưới đây là một số mã bạn có thể sử dụng (Tôi đang sử dụng 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; 
    } 

Dòng trong khối catch sẽ rethrow ngoại trừ NẾU ExPol1 định nghĩa nó. Nếu ExPol1 được cấu hình cho rethrow, thì ExceptionPolicy.HandleException sẽ trả về true. Nếu không, nó trả về false.

Bạn xác định phần còn lại trong cấu hình. XML trông khá khủng khiếp (không phải luôn luôn) nhưng bạn tạo ra điều này bằng cách sử dụng trình soạn thảo Cấu hình Thư viện Doanh nghiệp. Tôi chỉ cung cấp nó cho sự hoàn chỉnh.

Trong phần loggingConfiguration, tập tin này định nghĩa

  • nhật ký: a log file văn bản cán (bạn có thể sử dụng được xây dựng trong nhật ký sổ sự kiện, bảng sql, email, msmq và những người khác), với
  • một định dạng văn bản điều chỉnh như thế nào các thông số được ghi vào log (đôi khi tôi cấu hình này để viết tất cả mọi thứ để một dòng, lần khác trải rộng trên nhiều),
  • một loại đơn "General"
  • một nguồn đặc biệt mà bẫy bất kỳ lỗi nào trong cấu hình/entlib và repo rts họ là tốt. Tôi khuyên bạn nên làm điều này.

Trong phần exceptionHandling, nó định nghĩa

  • một chính sách duy nhất: "ExPo1", mà xử lý gõ ArgumentNullExceptions và quy định cụ thể postHandlingAction của None (ví dụ: không rethrow).
  • một handler mà đăng nhập vào ngạch chung (định nghĩa ở trên)

tôi không làm điều đó trong ví dụ này, nhưng bạn cũng có thể thay thế một ngoại lệ với một kiểu khác nhau sử dụng một chính sách.

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

Không phải là nó một chút thô lỗ tới -1 cái gì đó mà không giải thích? Tôi đã làm gì sai? – serialhobbyist

Các vấn đề liên quan