If you work with server technologies and applications you know how important to have reliable logging system which will allow to monitor work and find problems if something went wrong. Sharepoint is not exception. It has flexible ULS (unified logging service) with many configuration options (I recommend to use convenient tool for reading Sharepoint logs: ULS Viewer. It allows to filter events of different types and displays critical errors with red color which will attract your attention faster).
Sometimes ULS is not enough however. You may need to use Windows event viewer as reserve logging system – e.g. write all errors and warnings both to ULS and to event log, while information messages can be written only to ULS. In event log errors are displayed more expressively so you will find it faster). In order to work with event viewer you may use logger from Microsoft Enterprise Library. It contains convenient wrappers and allows to write messages to the Windows event log like this:
In order to use Enterprise library logger you need to configure it first. Configuration is added to the config file and looks like this (I divided some rows on several lines in order to keep it within width of my blog layout. In the real config you should remove line breaks):
This configuration sections should be added to the web.config of the Sharepoint site. After that you will be able to write messages to the Windows event log from the context of the site (e.g. in codebehind of application layouts pages, user control or web part).
But what if you need to write messages to event log also from Sharepoint timer job? Is it possible to configure it by the same way? The answer is yes. As you probably know job is executed in the separate process (Sharepoint timer service). Executable owstimer.exe is located in 14/bin folder (12/bin in case of Sharepoint 2007). So in order to MS Enterprise library logger you have to create owstimer.exe.config file (or modify it if it is already exists) and add configuration to it like shown above. After that restart Sharepoint timer service from Administration > Services and run your job. You will see that it now writes messages to the Windows event log.