When I use the following code to write to Application Event log, everything works fine:
EventLog log = new EventLog();
log.Source = "Application";
log.WriteEntry("test message", EventLogEntryType.Error);
When I use the code that is from MSDN and all other blogs, I get the security error (I am guessing because CreateEventSource raises it).
string sSource = "MyWebService";
string sLog = "myApplication";
string sMsg = errorMessage;
if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);
EventLog.WriteEntry(sSource, sMsg, EventLogEntryType.Error);
So, do I need to check whether the source exists if all I need is to write to Application log which is there by default?
What is the proper way to write to EventViewer?
The CreateEventSource method create a new source in the event log, this allow you to write log of your application in the application own group instead of writing in the generic Application
group.
Maybe you get an error because the user that you using to create the event source doesn't have the permission to create it, try to run your program as administrator if you are under Vista/7 OS.
The proper way to log in the event viewer depends on your needs, if your application generates a lot of logging message and you want to group this log in an application specific container, maybe it is better to create an application specific log event source and write the log in it, instead if your application generates few log messages and there is no need to group them together you can use the the generic Application
log event source ...
I suggest you try log4net, in case you want to write to different sources as well (smtp, file, etc.)
http://logging.apache.org/log4net/release/config-examples.html#eventlogappender
For web apps:
General use:
Similar solution for winforms/windows service.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With