Search code examples
c#loggingevent-log

Setting event log properties just after creating the event source


I have some code that creates a new event source:

EventLog.CreateEventSource(Source, LogName);

I know that there's a latency to creating this. I would like to set some default EventLog properties. I'm thinking something along the lines of:

EventLog log = new EventLog();
log.Source = Source;
log.MaximumKilobytes = 16384;
log.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 0);

Is there some creative way of doing this at the same time?

I suppose I could periodically check EventLog.Exists(...) until it returns true, but it seems like there must be a cleaner way.


Solution

  • This post is old, but I came here by searching with google, and thought this might be useful.

    If you are creating an event log source (instead of a new event log), the settings you are applying with ModifyOverflowPolicy are actually for the whole event log and not for the source you've just created.

    Therefore you should be able to do this:

    string LogName = "Application";
    EventLog.CreateEventSource(Source, LogName);
    
    EventLog log = new EventLog(LogName);
    log.MaximumKilobytes = 16384;
    log.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 0);
    

    The property log.Source is only used if you're going to write to the log: http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.source.aspx

    Else, you can write an informational log (e.g. Event Log created) to force the log creation:

    the log is not created until the first entry is written to it. http://msdn.microsoft.com/en-us/library/2awhba7a.aspx