Creating and deleting event logs with C# .NET
October 12, 2017 Leave a comment
The Windows event viewer contains a lot of useful information on what happens on the system:
Windows will by default write a lot of information here at differing levels: information, warning, failure, success and error. You can also write to the event log, create new logs and delete them if the code has the EventLogPermission permission. However, bear in mind that it’s quite resource intensive to write to the event logs. So don’t use it for general logging purposes to record what’s happening in your application. Use it to record major but infrequent events like shutdown, severe failure, start-up or any out-of-the-ordinary cases.
There are some predefined Windows logs in the event log: Application, Security and System are the usual examples. However, you can create your own custom log if you wish. The key is the EventLog object located in the System.Diagnostics namespace:
string source = "DemoTestApplication"; string log = "DemoEventLog"; EventLog demoLog = new EventLog(log); demoLog.Source = source; demoLog.WriteEntry("This is the first message to the log", EventLogEntryType.Information);
The new log type was saved under the Applications and Services log category:
You’ll probably have to restart the Event Viewer to find the new log type.
You can write to one of the existing Windows logs as well by specifying the name of the log. So we can create a log source within the Application log as follows:
string source = "DemoSourceWithinApplicationLog"; string log = "Application"; if (!EventLog.SourceExists(source)) { EventLog.CreateEventSource(source, log); } EventLog.WriteEntry(source, "First message from the demo log within Application", EventLogEntryType.Information);
The log entry is visible within the Application log:
It’s very easy to delete your custom log:
string log = "DemoEventLog"; EventLog.Delete(log);
The log will be deleted. Again, you’ll have to restart the event viewer to see that changes.
You can view all posts related to Diagnostics here.