开发者

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 s开发者_C百科omething 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.


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


Just tried this and as far as I can tell, the ModifyOverflowPolicy() call is not needed just to set the maximum file size. Also, the minimum size seems to be 1 MB even though the call accepts lower values. Any accepted value is stored in the registry (in bytes) but GUI and tests shows that 1028 kB is the minimum. Worth noting is that the GetEventLogs() call returns the size derived from the registry, not the actual 1 MB limit.

if (!System.Diagnostics.EventLog.SourceExists(this.eventSourceName))
{
    System.Diagnostics.EventLog.CreateEventSource(this.eventSourceName, this.eventLogName);
    if (!string.IsNullOrEmpty(this.eventLogMaxSizeKB))
    {
        System.Diagnostics.EventLog myEventLog = new System.Diagnostics.EventLog(this.eventLogName);
        long RoundedToLowest64k = (long.Parse(this.eventLogMaxSizeKB) / 64) * 64;
        myEventLog.MaximumKilobytes = RoundedToLowest64k;
    }
}

Tested on Windows 7 64-bit and 2008 R2 64-bit. I also noted that the actual file size is 4 kB larger than what you set. In the GUI this is visible for the minimum size, 1028 kByte, but all larger values are multiples of 64 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜