C # event logging - do I need to use EventLog.CreateEventSource when writing to the application log?

When I use the following code to write to the application event log, everything works fine:

EventLog log = new EventLog(); log.Source = "Application"; log.WriteEntry("test message", EventLogEntryType.Error); 

When I use code from MSDN and all other blogs, I get a security error (I assume 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, I need to check if the source exists, if all I need is to write to the application log, which is by default?

What is the correct way to record in EventViewer?

+8
c # event-log event-viewer
source share
6 answers

The CreateEventSource method creates a new source in the event log, this allows you to write the log of your application to your own application group instead of writing to the general Application group.

Perhaps you received an error message because the user who uses to create the event source does not have permission to create it, try running your program as an administrator if you are on Vista / 7 OS.

The correct way to log into the event viewer depends on your needs, if your application generates a lot of log messages and you want to group this log into a specific container, it might be better to create a specific source log event and write it to the log instead, if your the application generates several log messages, and there is no need to group them together, you can use the Application ...

+7
source share

I suggest you try log4net if you want to write to different sources (smtp, file, etc.)

http://logging.apache.org/log4net/release/config-examples.html#eventlogappender

For web applications:

General use:

A similar solution for the winforms / windows service.

+2
source share

You must have administrator privileges to create an event source. In the first case, you are not using a custom source.

+2
source share

Direct WriteEntry will go to the default application source. SourceExists and CreateEventSource is if you want to create your own custom source, which will make it easier to find any log entries in the event viewer.

And yes, you must have permission to create a client event source, as others have mentioned.

+1
source share

To run the application, you must have administrator rights.

Or you can start the application by going to the debug folder of your application and right-click on your .exe file and run it as admin

or

You start Visual Studio as admin

0
source share

You do not need to create an event source. This can be a big advantage when generating events that are language-independent or have permutations, but not necessary, at least for .NET programs (BCL provides a default event source).

-one
source share

All Articles