65.9K
CodeProject is changing. Read more.
Home

How to write custom log and source for custom log in C#

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.67/5 (8 votes)

Jun 13, 2007

1 min read

viewsIcon

39260

downloadIcon

349

It will show you the way for writing custom log in C#.Net

Introduction

This article will introduce you how to write custom log event for your tool/program. If you are going to create a tool then most of the professional like to use event log for logging its information, error etc and user can view these log in event log viewer.

Background:

Whenever you are going to create custom event log it creates registry entry in HKLM/ SYSTEM/ Services/ Eventlog.

For example if you are going to create custom log "MyLog" then the registry entry for MyLog will be HKLM/ SYSTEM/ Services/ Eventlog/MyLog and event file will be stored in %SystemRoot%\System32\config\Biopassw.evt path.

If you want to change the path for event log file then you have to change the path in File key of event log.

Using the code

Here the code :)

 
//Class for create custom log
using System.Diagnostics;
namespace EventExp
{
    class MyLog
    {
        //
        //create string object for source,log and event.
        //
        string mySource;
        string myLog;
        string myEvent;
        public MyLog()
        {
            //
            //assign text to source,log and event string.
            //
            mySource = "Sample Application";
            myLog = "MyLog";
            myEvent = "Sample Event";
        }
        public void CreateMyLog()
        {
            //
            //Check the event log if not exist then create it.
            //
            if (!EventLog.SourceExists(mySource))
            {
                EventLog.CreateEventSource(mySource, myLog);
            }
        }
        public void WriteMyLogEntry()
        {
            //
            //Will write entry in MyLog vent log.
            //
            EventLog.WriteEntry(mySource, myEvent);
            EventLog.WriteEntry(mySource, myEvent,
                EventLogEntryType.Warning, 234);
        }
    }
}
In program.cs inside main function:
//
            //Now write custom log
            //
            MyLog objectMylog = new MyLog();
            objectMylog.CreateMyLog();
            objectMylog.WriteMyLogEntry();


In event viewer we can see the log "MyLog" having two event log entry for Mylog written by WriteMyLogEntry function.

Points of Interest

When you creates source for log it writes mapping in side registry. Once you created source and if you want to change that source for other system or custom log then after creating the source with new custom/system event log you must have to restart the system.