Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Simple Error Logging Util Class

0.00/5 (No votes)
16 May 2013 1  
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.

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