Click here to Skip to main content
Click here to Skip to main content

Really Simple Log Writer

, 25 May 2010 GPL3
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

Share

About the Author

Marco Manso
Technical Lead
Portugal Portugal
He is the Head of R&D in a Portuguese IT Company operating in Space and Security markets.
His responsibilities include team coordination, project management and system conceptualization. He also works in close partnership with Universities and R&D Centres, promoting joint activities, common projects and transfer of knowledge and technology.
He actively cooperates in international study and advisory groups of engineers and scientists.
He is graduated in Electronics and Computer Sciences by a Portuguese University and is post-graduated in Information Warfare/Competitive Intelligence.
In his free time, he enjoys lauching new endeavors and challenges.

Comments and Discussions

 
SuggestionA still simple, but more elaborated alternative based on your approach PinmemberJochen Scharr8-Jul-14 1:15 
GeneralGood..but think about this situation PinmemberYves31-May-10 19:59 
GeneralError when running Pinmemberloganj199926-May-10 3:21 
AnswerRe: Error when running PinmemberMarco Manso26-May-10 4:28 
GeneralRe: Error when running Pinmemberloganj199926-May-10 4:35 
GeneralRe: Error when running PinmemberMarco Manso26-May-10 4:59 
QuestionWhy not a method to read the Log? PinmemberRui Figueiredo25-May-10 22:10 
AnswerRe: Why not a method to read the Log? PinmemberMarco Manso26-May-10 12:49 
GeneralSuggestion Pinmemberabhi4u194713-May-10 21:48 
GeneralRe: Suggestion PinmemberMarco Manso17-May-10 0:34 
GeneralGreat simple and very useful code. PinmemberMember 348574012-May-10 14:55 
GeneralGood PinmvpLuc Pattyn11-May-10 15:07 
GeneralRe: Good PinmemberMarco Manso12-May-10 6:17 
GeneralRe: Good PinmvpLuc Pattyn12-May-10 6:26 
GeneralMy vote of 1 PinmemberAndyKernahan11-May-10 5:47 
GeneralRe: My vote of 1 Pinmemberjgauffin24-May-10 21:55 
GeneralRe: My vote of 1 PinmemberAndyKernahan25-May-10 4:09 
GeneralRe: My vote of 1 Pinmemberjgauffin25-May-10 4:47 
GeneralRe: My vote of 1 PinmemberAndyKernahan25-May-10 5:00 
GeneralRe: My vote of 1 PinmemberAjay Vijayvargiya25-May-10 17:59 
GeneralRe: My vote of 1 PinmemberAndyKernahan25-May-10 21:44 
GeneralRe: My vote of 1 PinmemberMarco Manso25-May-10 23:54 
GeneralGoal is keep it REALLY simple - yet effective PinmemberMarco Manso10-May-10 13:17 
GeneralUse NLog! PinmemberAlexCode10-May-10 9:49 
GeneralGood enough Pinmembermidascheck10-May-10 6:01 
GeneralSuggestion PinmemberSky Sanders10-May-10 5:20 
GeneralRe: Suggestion PinmemberMarco Manso10-May-10 13:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411023.1 | Last Updated 25 May 2010
Article Copyright 2010 by Marco Manso
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid