Click here to Skip to main content
15,867,756 members
Articles / Programming Languages / C#
Article

Logger in C# - An easy way for monitoring .NET applications

Rate me:
Please Sign up or sign in to vote.
4.62/5 (34 votes)
13 Apr 20032 min read 476.7K   8.9K   127   28
Logger is used to create a customized error log file or an error can be registered as a log entry in the Windows Event Log on the administrator's machine with ON/OFF logging facility.

Sample Image - Windows Event Log

Windows event log

Sample Image - Customized Event Log

Customized event log

Overview

Logger is used for creating customized error log files or an error can be registered as a log entry in the Windows Event Log on the administrator's machine. This article is demonstrating how to create a text based error log file along with error messages with your own format, using a C# class.

This class demonstrates the use of following namespaces.

  • System.IO
  • System.Net
  • System.Diagnostics
  • System.Xml

Installation step

Just download , add reference to your application, write single line of code in your application to use it.

Source code

This project will handle the following two steps:

  1. Creating customized error log file capturing for our application errors.
  2. Register the errors in Windows event log on the administrator's machine.

You can use any one of these error capturing mechanisms to monitor your applications.

The main idea is create a error log file based on input [path] we have given. If the file is not available, then Logger will create a log file named LogFile.txt under application directory. If the file is available, the it will update the error info into that file with necessary information.

C#
using System.IO;
using System.Net;

using System.Diagnostics; 

Before we make a function to create an error file, we have to declare some variables that will be used in our function. This is an example of variables declaration and the main function is ErrorRoutine.

C#
public static string strLogFilePath = string.Empty;
private static StreamWriter sw  = null;
/// <summary>
/// Setting LogFile path. If the logfile path is 
/// null then it will update error info into LogFile.txt under
/// application directory.
/// </summary>
public string LogFilePath
{
    set
    {
        strLogFilePath    = value;  
    }
    get    
    {
        return strLogFilePath;
    }
}

/// <summary>
/// Write error log entry for window event if the bLogType is true.
/// Otherwise, write the log entry to
/// customized text-based text file
/// </summary>
/// <param name="bLogType"></param>
/// <param name="objException"></param>
/// <returns>false if the problem persists</returns>
public static bool ErrorRoutine(bool bLogType,Exception  objException)
{
    try
    {
        //Check whether logging is enabled or not
        bool bLoggingEnabled =    false;
    
        bLoggingEnabled = CheckLoggingEnabled();

        //Don't process more if the logging 
        if (false == bLoggingEnabled)
            return true;

        //Write to Windows event log
        if (true == bLogType)
        {
            string EventLogName    = "ErrorSample";

            if (!EventLog.SourceExists(EventLogName))
                EventLog.CreateEventSource(objException.Message, 
                EventLogName);

            // Inserting into event log
            EventLog Log    = new EventLog();
            Log.Source        = EventLogName;
            Log.WriteEntry(objException.Message, 
                     EventLogEntryType.Error);
        }
        //Custom text-based event log
        else
        {
            if (false == CustomErrorRoutine(objException))
                return false;
        }
        return true;
    }catch(Exception)
    {
        return false;
    }
}

Here, LogFilePath property is used set the error log file path, where we want to create/reside that file. The main function ErrorRoutine will take two parameters. First one is Boolean, to decide window event log or customized error log. The parameter bLogType = true capture error information using Windows event log on the administrator's machine. Otherwise, error information will update in to text file.

C#
///<summary>
/// If the LogFile path is empty then, it will write the log entry to 
/// LogFile.txt under application directory.
/// If the LogFile.txt is not availble it will create it
/// If the Log File path is not empty but the file is 
/// not availble it will create it.
/// <param name="objException"></param>
/// <RETURNS>false if the problem persists</RETURNS>
///</summary>
private static bool CustomErrorRoutine(Exception objException)
{
    string strPathName    = string.Empty ;

    if (strLogFilePath.Equals(string.Empty))
    {
        //Get Default log file path "LogFile.txt"
        strPathName    = GetLogFilePath();
    }
    else
    {
        //If the log file path is not empty but the file
        //is not available it will create it
        if (true != File.Exists(strLogFilePath))
        {
            if (false == CheckDirectory(strLogFilePath))
               return false;

            FileStream fs = new FileStream(strLogFilePath,
                    FileMode.OpenOrCreate, FileAccess.ReadWrite);
            fs.Close();
        }
        strPathName    = strLogFilePath;
    }
    bool bReturn    = true;

    // write the error log to that text file
    if (true != WriteErrorLog(strPathName,objException))
    {
        bReturn    = false;
    }
    return bReturn;
}


/// <summary>
/// Write Source,method,date,time,computer,error 
/// and stack trace information to the text file
/// 
/// <param name="strPathName"></param>
/// <param name="objException"></param>
/// <RETURNS>false if the problem persists</RETURNS>
///</summary>
private static bool WriteErrorLog(string strPathName,
                                Exception  objException)
{
    bool bReturn        = false;
    string strException    = string.Empty;
    try
    {
        sw = new StreamWriter(strPathName,true);
        sw.WriteLine("Source        : " + 
                objException.Source.ToString().Trim());
        sw.WriteLine("Method        : " + 
                objException.TargetSite.Name.ToString());
        sw.WriteLine("Date        : " + 
                DateTime.Now.ToLongTimeString());
        sw.WriteLine("Time        : " + 
                DateTime.Now.ToShortDateString());
        sw.WriteLine("Computer    : " + 
                Dns.GetHostName().ToString());
        sw.WriteLine("Error        : " +  
                objException.Message.ToString().Trim());
        sw.WriteLine("Stack Trace    : " + 
                objException.StackTrace.ToString().Trim());
        sw.WriteLine("^^------------------------
                -------------------------------------------^^");
        sw.Flush();
        sw.Close();
        bReturn    = true;
    }
    catch(Exception)
    {
        bReturn    = false;
    }
    return bReturn;
}


/// <summary>
/// Check the log file in applcation directory.
/// If it is not available, creae it
/// 
/// <RETURNS>Log file path</RETURNS>
///</summary>
private static string GetLogFilePath()
{
    try
    {
        // get the base directory
        string baseDir =  AppDomain.CurrentDomain.BaseDirectory +
                       AppDomain.CurrentDomain.RelativeSearchPath;

        // search the file below the current directory
        string retFilePath = baseDir + "//" + "LogFile.txt";

        // if exists, return the path
        if (File.Exists(retFilePath) == true)
            return retFilePath;
            //create a text file
        else
        {
                if (false == CheckDirectory(strLogFilePath))
                     return  string.Empty;

                FileStream fs = new FileStream(retFilePath,
                      FileMode.OpenOrCreate, FileAccess.ReadWrite);
                fs.Close();
        }

        return retFilePath;
    }
    catch(Exception)
    {
        return string.Empty;
    }
}

/// <summary>
/// Create a directory if not exists
/// 
/// <param name="stLogPath"></param>
///<summary> <RETURNS></RETURNS>
private static bool CheckDirectory(string strLogPath)
{
    try
    {
        int nFindSlashPos  = strLogPath.Trim().LastIndexOf("\\");
        string strDirectoryname = 
                   strLogPath.Trim().Substring(0,nFindSlashPos);

        if (false == Directory.Exists(strDirectoryname))
            Directory.CreateDirectory(strDirectoryname);
        return true;
    }
    catch(Exception)
    {
        return false;

    }
}

ON/OFF logging

If you place LogginStaus.Config under application folder [\bin\debug or project] of your project then Logger read it's value to enable/disable logging. If the file is not available then enable the logging by default.

The LogginStatus.Config looks like this.

C#
<?xml version="1.0" encoding="utf-8" ?> 
<LoggingStatus>
<LoggingEnabled>0</LoggingEnabled>
</LoggingStatus>

0 for disable logging
1 for enable logging

/// <summary>
/// Check Logginstatus config file is exist.
/// If exist read the value set the loggig status
/// </summary>
private static bool CheckLoggingEnabled()
{
    string strLoggingStatusConfig    = string.Empty;
    
    strLoggingStatusConfig = GetLoggingStatusConfigFileName();
    
    //If it's empty then enable the logging status 
    if (strLoggingStatusConfig.Equals(string.Empty))
    {
        return  true;
    }
    else
    {
            
        //Read the value from xml and set the logging status
        bool bTemp    = GetValueFromXml(strLoggingStatusConfig);
        return bTemp;
    }
}

/// <summary>
/// Check the Logginstatus config under debug or 
/// release folder. If not exist, check under 
/// project folder. If not exist again, return empty string
/// </summary>
/// <RETURNS>empty string if file not exists</RETURNS>
private static string GetLoggingStatusConfigFileName()
{
    string strCheckinBaseDirecotry  = 
              AppDomain.CurrentDomain.BaseDirectory+ 
              "LoggingStatus.Config";

    if (File.Exists(strCheckinBaseDirecotry))
        return strCheckinBaseDirecotry;
    else
    {
        string strCheckinApplicationDirecotry  =  
            GetApplicationPath() + "LoggingStatus.Config";

        if (File.Exists(strCheckinApplicationDirecotry))
            return strCheckinApplicationDirecotry;
        else
            return string.Empty;
    }
}

///<summary> 
/// Read the xml file and getthe logging status
/// <param name="strXmlPath"></param>
///</summary> <RETURNS></RETURNS>
private static bool GetValueFromXml(string strXmlPath)
{
    try
    {
        //Open a FileStream on the Xml file
        FileStream docIn = new FileStream(strXmlPath,
           FileMode.Open,FileAccess.Read,FileShare.ReadWrite);

        XmlDocument contactDoc = new XmlDocument();
        //Load the Xml Document
        contactDoc.Load(docIn);

        //Get a node
        XmlNodeList UserList = 
            contactDoc.GetElementsByTagName("LoggingEnabled");

        //get the value
        string strGetValue= UserList.Item(0).InnerText.ToString(); 

        if (strGetValue.Equals("0"))
            return false;
        else if (strGetValue.Equals("1"))
            return true;
        else
            return false;
    }
    catch(Exception)
    {
        return false;
    }
}

To use this class, Just add a reference to your project and follow the steps and just import the Logger reference into you project.

This is a code behind C# for this page, I call the ErrorRoutine function from our class when exception is occurred. Writing log entry to customized text file:

C#
using Logger;

.
.
.
private void BtnFind_Click(object sender, System.EventArgs e)
{
    try
    {
        int i = 1;
        int j = 0;
        int k = i/j;
    }
    catch(Exception ee)
    {
        bool bReturnLog = false;
  
      ErrorLog.LogFilePath = "F:\\DotNetProjects\\
                       SampleLogFile\\ErrorLogFile.txt"; 
      //false for writing log entry to customized text file
      bReturnLog  = ErrorLog.ErrorRoutine(false,ee); 

        if (false == bReturnLog)
            MessageBox.Show("Unable to write a log");
    }
}

This is a code behind VB.NET for this page. Writing log entry to Windows event log:

VB
Imports Logger;

.

.
.
Private Sub Button1_Click(ByVal sender As System.Object, _
         ByVal e As System.EventArgs) Handles Button1.Click
        Try

            Dim i, j, k As Integer
            i = 1
            j = 0
            k = i / j

        Catch ex As Exception
            Dim bReturnLog As Boolean   
            //True for writing log entry to windows event log 
            bReturnLog  = ErrorLog.ErrorRoutine(True,ex)
            
           If (False == bReturnLog) Then
              MessageBox.Show("Unable to write a log")
           End If
        End Try
    End Sub

That's it. :-) You can use this for console, Winforms and web forms too.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
I am a system analyst and have been with Microsoft & Sun Technologies for more than 7 years. I have always been fascinated by java and .NET. I take lot of technical articles and writing them.

I am a Sun Certified Java Programmer for Java 2 Platform 1.4 , Web component developer Java 2 Platform - Enterprise Edition 1.4 and Microsoft certified developer using C#.NET in Web Development ASP.NET.

Visit my web site www.mohamedashraf.tk

Comments and Discussions

 
GeneralRe: Logging Alternative Pin
Laurent Kempé14-Apr-03 3:58
Laurent Kempé14-Apr-03 3:58 
GeneralRe: Logging Alternative Pin
Mike McPhail14-Apr-03 10:28
Mike McPhail14-Apr-03 10:28 
GeneralRe: Logging Alternative Pin
Laurent Kempé14-Apr-03 11:17
Laurent Kempé14-Apr-03 11:17 
GeneralRe: Logging Alternative [modified] Pin
MStanbrook15-Apr-03 7:09
MStanbrook15-Apr-03 7:09 
GeneralRe: Logging Alternative Pin
Anonymous28-Apr-03 17:32
Anonymous28-Apr-03 17:32 
GeneralRe: Logging Alternative Pin
mikelb30-Apr-03 4:45
mikelb30-Apr-03 4:45 
GeneralRe: Logging Alternative Pin
Ashraf Mohamed15-Apr-03 3:03
Ashraf Mohamed15-Apr-03 3:03 
GeneralRe: Logging Alternative Pin
MStanbrook15-Apr-03 7:06
MStanbrook15-Apr-03 7:06 
FYI:

You can find log4Net here: http://log4net.sourceforge.net/[^]

Mike Stanbrook
mstanbrook@yahoo.com
GeneralRe: Logging Alternative Pin
Anonymous19-Apr-04 23:32
Anonymous19-Apr-04 23:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.