Click here to Skip to main content
15,881,803 members
Articles / Programming Languages / C# 3.5
Tip/Trick

Simple Error Logging Util Class

Rate me:
Please Sign up or sign in to vote.
4.67/5 (5 votes)
16 May 2013CPOL 37.5K   4   5
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:

C#
//
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.

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Australia Australia
• Salesforce certified Consultant
• C# Developer since 2005
• SAP/ABAP Technical Consultant since Sep. 2010
• Has experience in .NET Framework, SQL, VFP

Comments and Discussions

 
QuestionHave you seen this alternative? Pin
Jochen Scharr20-Jun-14 2:21
Jochen Scharr20-Jun-14 2:21 
AnswerRe: Have you seen this alternative? Pin
Pasan Eeriyagama3-Jul-14 20:04
Pasan Eeriyagama3-Jul-14 20:04 
GeneralMy vote of 3 Pin
jeramyRR17-Jun-13 16:02
jeramyRR17-Jun-13 16:02 
GeneralRe: My vote of 3 Pin
Pasan Eeriyagama17-Jun-13 22:51
Pasan Eeriyagama17-Jun-13 22:51 
GeneralRe: My vote of 3 Pin
jeramyRR17-Jun-13 23:17
jeramyRR17-Jun-13 23:17 

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.