65.9K
CodeProject is changing. Read more.
Home

Simple Error Logging Util Class

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (5 votes)

May 16, 2013

CPOL
viewsIcon

38170

Simple Application Error Logging

Introduction

This tip describes a simple exception/custom message logger which can be used to log Application Errors, Logical Errors, etc. in an easy manner.

Background

The importance of having a static mechanism to log these messages came up with below:

  1. Repeatedly coded Error logging can be eliminated
  2. IO Errors, etc. needed to be handled while logging errors

Using the Code

Create the class and its implementation as below:

//
public class Functions_ErrorLog
    {
        public static String AppErrorLogFileName = "ErrorLog.txt";

        /// <summary>
        /// Log any messages from the Application
        /// </summary>
        /// <param name="message"></param>
        public static void LogMessage(String pMessage)
        {
            bool Successful = false;

            for (int idx = 0; idx < 10; idx++)
            {
                try
                {
                    // Log message to default log file.
                    StreamWriter str = new StreamWriter
                    (Functions_ConfigFileHandling.GetSettingsFolderLocation()
                        + Functions_ErrorLog.AppErrorLogFileName, true);

                    str.AutoFlush = true;   // Wri9te text with no buffering
                    str.WriteLine("Time: " + DateTime.Now.ToString() + 
                    Environment.NewLine
                        + "Message: " + pMessage);
                    str.Close();

                    Successful = true;
                }
                catch (Exception)
                {
                }

                if (Successful == true)     // Logging successful
                    break;
                else                        // Logging failed, retry in 100 milliseconds
                    Thread.Sleep(10);
            }
        }

        public static void LogMessage(Exception pExeption)
        {
            String str_inner = "";

            try
            {
                str_inner = Environment.NewLine +
                "Inner Exception Msg: " + pExeption.InnerException.Message +
                "Inner Exception Stack: " + pExeption.InnerException.StackTrace;
            }
            catch (Exception)
            {
            }

            LogMessage("Exception: " + pExeption.Message + Environment.NewLine +
                "Stack: " + str_inner);
        }
    } 

For keeping Error Logs in a specific config. folder, I have used another class in which methods are being called from above to determine the Error Log's Location.

public static string GetSettingsFolderLocation()
{
    // Config. folder path
    String folderpath = Environment.GetFolderPath
    (Environment.SpecialFolder.CommonApplicationData) + "\\EMP SW\\" +
         System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName + "\\";
         
    // Remove unnecessary extensions for folder name if any
    
    // Try creating folder if doesn't exist
    
    folderpath = folderpath.ToUpper().Replace
    (".VSHOST.EXE", "").Replace(".EXE", "");
    
    if (!Directory.Exists(folderpath))
    {
        try
        {
            Directory.CreateDirectory(folderpath);
        }
        catch (Exception ex)
        {
            // can't log error
            Functions_GUI.ShowMessageToEndUser
            ("NError occurred while initializing System settings, Please contact IT Support." +
                Environment.NewLine + "Error: " + 
                ex.Message + Environment.NewLine +
                "More: " + ex.StackTrace);
        }
    }
    
    return folderpath;
} 

In case while creating the error logging path, initially if it doesn't exist, it will create the config. folder to log the error.

Points of Interest

This was quite useful to have this implemented for apps so it was then easy to identify runtime exceptions as well as logical error logging by our apps all in one place.