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

Really Simple Log Writer

0.00/5 (No votes)
25 May 2010 4  
Code to write messages to a log file, in a very simple way.

Introduction

Logging is one of those tools a developer resorts to, to obtain awareness about how a program is executing and eventually (and hopefully) detecting coding faults. A lot of time may be saved when good logging is available.

I was looking for a simple way to implement logging into a program I was developing for fun, and after a few Google and CodeProject searches, I couldn't find a really simple way and, therefore, I decided to develop my own.

This small bit of code (80LOC, including headers, empty lines, dummy lines, and comments) allows an application to insert a message (string) into a file. Since I created it initially to track exceptions my application was raising, it also allows to write exceptions.

My main requirements were:

  • Don't require the need to instantiate any variable to log messages (hence, all methods are static).
  • Don't require any initialization code (outside this class, obviously).
  • Keep log file(s) 'small' but don't discard messages.
  • Keep it stupid simple (just call a method to write and that's it).

The Code

This simple code consists of a main class (ReallySimpleLog) and a global (static) variable that will keep the base directory of the 'user' application. In this way, the log file is stored in the same place the executable is located (and we can be sure that the directory exists).

The necessary initialization code is contained in a static constructor. In it, the application base directory is obtained by calling AppDomain.CurrentDomain.BaseDirectory + AppDomain.CurrentDomain.RelativeSearchPath.

The initial lines of the program are as follows:

public class ReallySimpleLog
{
    static string m_baseDir = null;


    static ReallySimpleLog()
    {
         m_baseDir = AppDomain.CurrentDomain.BaseDirectory +
                AppDomain.CurrentDomain.RelativeSearchPath;
    }

The constructor is static and initializes m_baseDir (the static constructor executes before any method of the class is used, and is run at most once during a single program instantiation - very handy).

The next step is to make this class useful: we create the following methods to store log messages.

public static void WriteLog(String message)
public static void WriteLog(Exception ex)

Since I wanted to keep log files to an acceptable size, I opted to create a file per day (you may easily change the period to an acceptable one). Furthermore, so that I could understand to which time period the log file would correspond, I created a method that creates a filename as follows: year-month-day-suffix-extension.

The method code is the following (keep it public - who knows if others may use it):

public static string GetFilenameYYYMMDD(string suffix, string extension)
{
    return System.DateTime.Now.ToString("yyyy_MM_dd")+suffix + extension;
}

Having this as background, here follows the main methods:

  • WriteLog (string message) writes a string message to the log. Note also that the file is closed after the write operation. In this way, we ensure that the log entry is available if, for example, the application crashes.
  • public static void WriteLog(String message)
    {
        //just in case: we protect code with try.
        try
        {
            string filename = m_baseDir
                + GetFilenameYYYMMDD("_LOG", ".log");
            System.IO.StreamWriter sw = new System.IO.StreamWriter(filename, true);
            XElement xmlEntry = new XElement("logEntry",
                new XElement("Date", System.DateTime.Now.ToString()),
                new XElement("Message", message));
            sw.WriteLine(xmlEntry);
            sw.Close();
        }
        catch (Exception)
        {
        }
    }

    The code is protected with a try-catch just for safety (we don't want to terminate the application if the log fails, but you may add an output-capability to trace the error).

    Note that the way to create (or append) to the log file is very simple: the second argument (set to true) of the StreamWriter constructor creates a file if it doesn't exist already. Then, just by calling WriteLine, a line with the message is appended.

  • WriteLog (Exception ex) is very similar to the previous method, but writes an exception (instead of a string) to the log.
  • public static void WriteLog(Exception ex)
    {
        //just in case: we protect code with try.
        try
        {
            string filename = m_baseDir
                + GetFilenameYYYMMDD("_LOG", ".log");
            System.IO.StreamWriter sw = new System.IO.StreamWriter(filename, true);
            XElement xmlEntry = new XElement("logEntry",
                new XElement("Date", System.DateTime.Now.ToString()),
                new XElement("Exception",
                    new XElement("Source", ex.Source),
                    new XElement("Message", ex.Message),
                    new XElement("Stack", ex.StackTrace)
                 )//end exception
            );
            //has inner exception?
            if (ex.InnerException != null)
            {
                xmlEntry.Element("Exception").Add(
                    new XElement("InnerException",
                        new XElement("Source", ex.InnerException.Source),
                        new XElement("Message", ex.InnerException.Message),
                        new XElement("Stack", ex.InnerException.StackTrace))
                    );
            } 
            sw.WriteLine(xmlEntry);
            sw.Close();
        }
        catch (Exception)
        {
        }
    }

    Note that an inner-exception may include more inner exceptions. A for-loop may be added if you intend to list all exceptions.

How to Use it

That's the beauty of it. If you remember, all attributes and methods are static, hence, no instances have to be created. Whenever you have something you want to log, just do (assuming you have all imports right):

For strings:

LogFile.WriteLog(message);   //where message is of type String

The following output is generated:

<logEntry>
  <Date>17-05-2010 09:58:31</Date>
  <Message>START</Message>
</logEntry>

For exceptions:

LogFile.WriteLog(exception); //where exception is of type Exception

The following output is generated (I used an example I had - sorry - it's in Portuguese - but you see the point):

<logEntry>
  <Date>15-05-2010 14:33:36</Date>
  <Exception>
    <Source>System</Source>
    <Message>O tempo limite da operação expirou</Message>
    <Stack>   em System.Net.HttpWebRequest.GetResponse()
      em WeAreServicesLib.HTTPSubsystemService.Download() 
      em C:\software\development\WeAre\WeAreServicesLib\HTTPSubsystemService.cs:line 120
    </Stack>
  </Exception>
</logEntry>

Note that the file is generated automatically (for my example, it is named '2010_05_15_LOG.log') - and each day, a new log file is generated (so that we don't worry about size).

OK - that's it. Have fun!

(I think this article has more lines than source-code itself ...).

Updates since first edition

Although it's a simple approach, it was very rewarding for me to receive further constructive feedback from other developers towards perfecting the approach used. Hereby follows some of the updates (with my acknowledgments):

  • Sky Sanders: output log in well-formed XML.
  • Luc Pattyn: determine date as "System.DateTime.Now.ToString("yyyy_MM_dd_");"
  • abhi4u1947: add details of InnerException also.

Thank you guys!

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