Click here to Skip to main content
15,113,295 members
Articles / Programming Languages / C# 3.5
Tip/Trick
Posted 15 May 2013

Stats

34.5K views
4 bookmarked

Simple Error Logging Util Class

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

Share

About the Author

Pasan Eeriyagama
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 3:21
MemberJochen Scharr20-Jun-14 3:21 
AnswerRe: Have you seen this alternative? Pin
Pasan Eeriyagama3-Jul-14 21:04
MemberPasan Eeriyagama3-Jul-14 21:04 
GeneralMy vote of 3 Pin
jeramyRR17-Jun-13 17:02
MemberjeramyRR17-Jun-13 17:02 
GeneralRe: My vote of 3 Pin
Pasan Eeriyagama17-Jun-13 23:51
MemberPasan Eeriyagama17-Jun-13 23:51 
GeneralRe: My vote of 3 Pin
jeramyRR18-Jun-13 0:17
MemberjeramyRR18-Jun-13 0: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.