Do you mean Windows System Log?
Yes, this is not so easy to understand. You need to install your own Event Source.
using System.Diagnostics;
internal class DefinitionSet {
internal const int MaximumLogSizeKilobytes = 2048;
}
public class EventLogInstallationHelper {
public EventLogInstallationHelper(
string applicationName, string eventLogName) {
this.EventLogName = eventLogName;
this.ApplicationName = applicationName;
}
public void Install() {
if ((!string.IsNullOrEmpty(ApplicationName)) &&
(!string.IsNullOrEmpty(EventLogName)))
EventLog.CreateEventSource(
ApplicationName,
EventLogName);
EventLog log = new EventLog(EventLogName);
log.MaximumKilobytes = DefinitionSet.MaximumLogSizeKilobytes;
log.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 0);
}
public void Uninstall() {
if (!string.IsNullOrEmpty(EventLogName)) {
EventLog deletingLog = new EventLog(EventLogName);
deletingLog.Clear();
}
if (!string.IsNullOrEmpty(ApplicationName))
EventLog.DeleteEventSource(ApplicationName);
result |= true;
if (!string.IsNullOrEmpty(EventLogName))
EventLog.Delete(EventLogName);
result |= true;
}
string ApplicationName, EventLogName;
}
The non-trivial part here is exception. You should deal with the case when you install Event Source if it is already done and uninstall when it is not installed.
Now, this is an example of the usage:
string Application = "Event Log Test";
string EventLogName = "CodeProject";
EventLogInstallationHelper helper =
new EventLogInstallationHelper(
Application,
EventLogName);
try {
helper.Install();
} catch {
System.Console.WriteLine("Event Log already installed");
}
EventLog.WriteEntry(Application, "some log");
EventLog.WriteEntry(Application, "some warning", EventLogEntryType.Warning);
EventLog eventLog = new EventLog();
eventLog.Source = Application;
eventLog.WriteEntry("another log");
eventLog.WriteEntry("some error", EventLogEntryType.Error);
System.Console.WriteLine("See event log now, then press any key");
System.Console.ReadKey(true);
try {
helper.Uninstall();
} catch {
System.Console.WriteLine("Event log already uninstalled");
}
The idea here is that you can have
EventLogName
name, it represents all your logging applications in one separate folder. Another name,
Application
, will represent a name of one of your application as a source in each log's properties.
This code is well tested.
—SA