C# 将异常写入 Windows 日志文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1184059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing Exceptions to the Windows Log File
提问by Gold
I'd like to catch my exceptions and log them in the Windows log file. How do I go about opening and writing to the Windows log?
我想捕获我的异常并将它们记录在 Windows 日志文件中。如何打开和写入 Windows 日志?
采纳答案by Doctor Jones
You can use the System.Diagnostics.EventLog.WriteEntryfunction to write entries to the event log.
您可以使用System.Diagnostics.EventLog.WriteEntry函数将条目写入事件日志。
System.Diagnostics.EventLog.WriteEntry("MyEventSource", exception.StackTrace,
System.Diagnostics.EventLogEntryType.Warning);
To read event logs you can use the System.Diagnostics.EventLog.GetEventLogsfunction.
要读取事件日志,您可以使用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
}
}
回答by Jon Galloway
Here's the simple answer on writing to the event log: http://support.microsoft.com/kb/307024
这是写入事件日志的简单答案:http: //support.microsoft.com/kb/307024
A better answer is to use something like log4net, which will handle that for you.
更好的答案是使用log4net 之类的东西,它会为您处理。
回答by Darin Dimitrov
Windows uses the Event log to trace activity. You can use the System.Diagnostics.Trace
class:
Windows 使用事件日志来跟踪活动。您可以使用System.Diagnostics.Trace
该类:
var traceSwitch = new TraceSwitch("MySwitch", "");
var exception = new Exception("Exception message");
if (traceSwitch.TraceError)
{
Trace.TraceError(exception);
}
And you can use app.config to instruct the logger where to write:
你可以使用 app.config 来指示记录器在哪里写:
<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>
回答by serialhobbyist
You can also consider using the Enterprise Library. It looks complicated to start with but an hour or two of playing will pay off. Config is stored in app.config so you can change it without recompiling - this can be really handy when you've got the same code sitting on test and live servers with different config. You can do quite a lot without loads of code.
您还可以考虑使用企业库。开始看起来很复杂,但玩一两个小时就会有回报。Config 存储在 app.config 中,因此您无需重新编译即可更改它 - 当您将相同的代码放在具有不同配置的测试和实时服务器上时,这会非常方便。你可以在没有大量代码的情况下做很多事情。
One nice thing is that you can define Exception policies so that exceptions are automatically logged. Here's some code you might use (I'm using EntLib 4.1):
一件好事是您可以定义异常策略,以便自动记录异常。这是您可能会使用的一些代码(我使用的是 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;
}
The line in the catch block will rethrow the exception IF the ExPol1 defines it. If ExPol1 is configured for rethrow, then ExceptionPolicy.HandleException will return true. If not, it returns false.
如果 ExPol1 定义了异常,catch 块中的行将重新抛出异常。如果 ExPol1 配置为重新抛出,则 ExceptionPolicy.HandleException 将返回 true。如果不是,则返回 false。
You define the rest in config. The XML looks pretty horrible (doesn't it always) but you create this using the Enterprise Library Configuration editor. I'm just supplying it for completeness.
您在配置中定义其余部分。XML 看起来非常糟糕(并非总是如此),但您可以使用 Enterprise Library Configuration 编辑器创建它。我只是为了完整性而提供它。
In the loggingConfiguration section, this file defines
在 loggingConfiguration 部分,此文件定义
- the log: a rolling text log file (you can use the built in windows event logs, sql tables, email, msmq and others), with
- a text formatter that governs how the parameters are written to the log (sometimes I configure this to write everything to one line, other times spread across many),
- a single category "General"
- a Special Source which traps any errors in the config/entlib and reports them as well. I strongly advise you to do this.
- 日志:滚动文本日志文件(您可以使用内置的 Windows 事件日志、sql 表、电子邮件、msmq 等),带有
- 控制参数如何写入日志的文本格式化程序(有时我将其配置为将所有内容都写入一行,有时则分布在许多行中),
- 单一类别“一般”
- 一个特殊源,它捕获 config/entlib 中的任何错误并报告它们。我强烈建议你这样做。
In the exceptionHandling section, it defines
在 exceptionHandling 部分,它定义了
- a single policy: "ExPo1", which handles type ArgumentNullExceptions and specifies the postHandlingAction of None (i.e. don't rethrow).
- a handler which logs to the General category (defined above)
- 单个策略:“ExPo1”,它处理类型 ArgumentNullExceptions 并指定 None 的 postHandlingAction(即不重新抛出)。
- 记录到 General 类别(如上定义)的处理程序
I don't do it in this example, but you can also replace an exception with a different type using a policy.
我在这个例子中没有这样做,但你也可以使用策略用不同的类型替换异常。
<?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>
回答by CrazyTim
These articles explain how to automatically log unhandedexceptions that might occur:
这些文章解释了如何自动记录可能发生的未经处理的异常:
VB.NET: http://visualbasic.about.com/od/usingvbnet/a/logging.htm
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#