How to store event log in Folder

2020-02-09 14:15发布

问题:

On an ASP NET project (C#) I'm using the System.Diagnostics namespace to log errors, warning and information. Using Windows 7 I see that the log I've set for the project is under "Applications and Services Logs". How can I set in code to create a folder and put it under "Applications and Services Logs[SOME FOLDER]\Applications and Services Logs", for examples?

回答1:

When creating your Event Source, specify a Log Name. It will become the "folder" in the Event Viewer.

EventLog.CreateEventSource("Source", "Log name");
EventLog.WriteMessage("Source", "Your message");

Be aware that creating an event source may require additional rights on the machine. In an ASP.Net context, I suggest to create a windows or console application that create the Event Source. Run it once as an administrator.



回答2:

The logs stored in the Applications and Services Log section are the logs of custom event publishers as opposed to simple Windows Event Logs.

From this article Technology Summary for Reading and Managing Event Logs:

Applications and Services logs are a different category of event logs than the Windows Logs. The Applications and Services logs store events from a single application or component rather than events that might have system-wide impact. They have a variety of names that are defined by event providers.

Thus, you would need to create a custom Event Publisher. Here are a couple of articles with more information:

  • Developing Event Publishers
  • Developing Using Event Reporting and Tracing


回答3:

This is a new feature of .NET 3.5 and available in . Microsoft introduced a new library that is not too user friendly read about it here. It says, most likely out of date, that these classes only work in Windows Vista, however I would hazard a guess that they are accessible in Windows 7 and Server 2008.

I didn't find code there to explain how to create a new hierarchy like you were asking for, however, I believe this in the general direction.



回答4:

Have you considered using a more generic log mechanism which provides greater flexibility? For example log4net. Then you can switch between log files and event log and also other methods whenever you want without changing a line of code.