Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to event log in C# - do I need to use EventLog.CreateEventSource when writing to Application log?

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?

like image 716
sarsnake Avatar asked Oct 31 '11 23:10

sarsnake


2 Answers

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 ...

like image 71
aleroot Avatar answered Sep 24 '22 17:09

aleroot


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:

  • http://haacked.com/archive/2005/03/07/ConfiguringLog4NetForWebApplications.aspx

General use:

  • http://mitch-wheat.blogspot.com/2007/04/log4net-net-logging-tool.html

Similar solution for winforms/windows service.

like image 44
Luke Hutton Avatar answered Sep 22 '22 17:09

Luke Hutton