How do you open the event log programatically?

2020-03-06 08:01发布

问题:

I'm logging errors to the event log using the usual:

 System.Diagnostics.Trace.TraceError("<" + purpose + "><time>" + DateTime.Now.ToUniversalTime() + "</time><message>" + message + "</message></" + purpose + ">");

and am wondering if there is a way to call this log file and display it for the user (either in my own format or by opening the event log file directly as does 'Event Viewer').

I've found the file in %SystemRoot%\System32\Winevt\Logs\mylog.evtx but not sure whether I should be approaching it this way or not. Ideally I'd like to emulate what the Event Viewer does but customised for my application.

回答1:

Try System.Diagnostics.EventLog

For Example, you can view entries in the applications log as follows

var log = EventLog.GetEventLogs().Where(x => x == "Application").First();
foreach (var entry in log.Entries) {
  // Do something with the entry
}


回答2:

I haven't tried seeing how accessible the data in the event log is in Vista/Win Server 2k8 (*.evtx), but the MMC console is extensible so you can write your own MMC plugin now. So if you did end up writing your own version of EventVwr.msc, it's easy as pie now.

http://msdn.microsoft.com/en-us/library/ms692759(VS.85).aspx

What is it that you're wanting to do in your customized log viewer thats missing from the current functionality?