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?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
You can use the System.Diagnostics.EventLog.WriteEntry function to write entries to the event log.
To read event logs you can use the System.Diagnostics.EventLog.GetEventLogs function.
Windows uses the Event log to trace activity. You can use the
System.Diagnostics.Trace
class:And you can use app.config to instruct the logger where to write:
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.
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):
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.
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.
In the loggingConfiguration section, this file defines
In the exceptionHandling section, it defines
I don't do it in this example, but you can also replace an exception with a different type using a policy.
These articles explain how to automatically log unhanded exceptions that might occur:
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#
Here's the simple answer on writing to the event log: http://support.microsoft.com/kb/307024
A better answer is to use something like log4net, which will handle that for you.