Is there a way to tell which EventLog caused the EntryWritten event in C#?
I think the problem is, that the whole concept of the EventLog
class is that it assumes it works upon a single Log - which it does. So neither the EventWrittenEventArgs
nor the EventEntry
class sport a member that contains the Log-name, as it is implicitly given by the associated EventLog-instance. Bad is of course, that you cannot get to it inside the EventWritten-handler.
You could create a wrapper around System.Diagnostics.EventLog
, like so:
class MyEventLog : EventLog
{
public MyEventLog(string logName, string machineName)
: base(logName, machineName)
{
base.EnableRaisingEvents = true;
base.EntryWritten += MyEventLog_EntryWritten;
}
void MyEventLog_EntryWritten(object sender, EntryWrittenEventArgs e)
{
Console.WriteLine("Entry in {0} log.", base.Log);
// Your code
}
}
Then use MyEventLog
in places where you normally would use EventLog
. Probably give it a better name though.
You could also factor out the "Your Code" part by providing an Action<string, EntryWrittenEventArgs>
property that is being called from inside MyEventLog_EntryWritten
and can be set to your "external" handler function.
Another option would be to use reflection along these lines:
string log = (string)sender.GetType().GetProperty("Log").GetValue(sender, null);
since sender
in this case actually has the Log
property.
I think that what you are looking for can be found in the EntryWrittenEventArgs.
The MSDN shows there is a property called Entry that shows you all kinds of information about what just got logged. There are some properties that might help you in the EventLogEntry class, such as MachineName or UserName.
Here is a link to the Args class http://msdn.microsoft.com/en-us/library/system.diagnostics.entrywritteneventargs.aspx
Here is a link to the Entry class http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlogentry.aspx
I don't see a direct link to the specific event log, but if you poke around in that class with the debugger the Entry object might give you enough information to look it up.
I hope this helps some.