Tôi muốn nắm bắt các ngoại lệ của mình và ghi lại chúng trong tệp nhật ký Windows. Làm thế nào để tôi mở và ghi vào nhật ký Windows?Viết ngoại lệ cho Tệp nhật ký Windows
Trả lời
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
}
}
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.
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>
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}; 
 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 & 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>
Những bài viết này giải thích làm thế nào để tự động đăng nhập unhanded trường hợp ngoại lệ có thể xảy ra:
VB.NET: http://visualbasic.about.com/od/usingvbnet/a/logging.htm
C#: Where to write the functions of ApplicationEvents.vb when converting project to C#
- 1. Viết ngoại lệ cho tệp
- 2. Cách viết nhật ký lỗi hoặc ngoại lệ vào tệp trong java
- 3. ngoại lệ ghi nhật ký trong C#
- 4. Viết/Đọc cho Nhật ký Sự kiện Windows
- 5. Ghi nhật ký ngoại lệ không được xử lý cho Windows Forms
- 6. Ghi nhật ký ngoại lệ SignalR?
- 7. log4Net tệp nhật ký không viết
- 8. Capybara: dấu vết ngoại lệ trong nhật ký
- 9. Bạn có viết ngoại lệ cho các vấn đề cụ thể hoặc ngoại lệ chung không?
- 10. Trình ghi nhật ký ngoại lệ: Thực tiễn tốt nhất
- 11. Cách viết từ Java vào Nhật ký sự kiện Windows?
- 12. Ghi nhật ký ngoại lệ bằng cách sử dụng Log4Net
- 13. Nhật ký sự kiện Windows vs Nhật ký văn bản
- 14. Tại sao .NET không ghi nhật ký ngăn xếp cho các ngoại lệ StackOverflow?
- 15. Làm thế nào để xuất thông tin ngoại lệ trong tệp nhật ký với log4php?
- 16. Định dạng để viết tệp nhật ký JSON?
- 17. Viết vào một tệp nhật ký trong ASP.NET
- 18. Thực tiễn tốt nhất cho các dịch vụ GWT ngoại lệ ghi nhật ký
- 19. Nơi lưu trữ tệp nhật ký ứng dụng trên Windows
- 20. Nhật ký nhắc lệnh Windows vào một tệp
- 21. Viết nhật ký vào tập tin
- 22. ghi nhật ký log4net không tạo tệp nhật ký
- 23. Các vị trí tốt nhất để viết nhật ký lỗi trong Windows ở đâu?
- 24. Viết cho Nhật ký sự kiện trong Delphi
- 25. Kiểm soát hành trình .Net ngoại lệ viết msbuild-results.xml
- 26. C Syslog.h không viết nhật ký
- 27. Ngoại lệ khi chạy Jenkins trên Windows
- 28. Ghi nhật ký ngoại lệ ASP.Net MVC kết hợp với xử lý lỗi
- 29. after_filter cho trường hợp ngoại lệ
- 30. Nhật ký thời gian chạy Ngoại lệ trong Java bằng cách sử dụng log4j
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