Click here to Skip to main content
Licence GPL3
First Posted 10 May 2010
Views 16,821
Downloads 119
Bookmarked 45 times

Really Simple Log Writer

By | 25 May 2010 | Article
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)

About the Author

Marco Manso

Technical Lead

Portugal Portugal

Member

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.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralGood..but think about this situation PinmemberYves18:59 31 May '10  
GeneralError when running Pinmemberloganj19992:21 26 May '10  
AnswerRe: Error when running PinmemberMarco Manso3:28 26 May '10  
GeneralRe: Error when running Pinmemberloganj19993:35 26 May '10  
GeneralRe: Error when running PinmemberMarco Manso3:59 26 May '10  
QuestionWhy not a method to read the Log? PinmemberRui Figueiredo21:10 25 May '10  
AnswerRe: Why not a method to read the Log? PinmemberMarco Manso11:49 26 May '10  
GeneralSuggestion Pinmemberabhi4u194720:48 13 May '10  
GeneralRe: Suggestion PinmemberMarco Manso23:34 16 May '10  
GeneralGreat simple and very useful code. PinmemberMember 348574013:55 12 May '10  
GeneralGood PinmvpLuc Pattyn14:07 11 May '10  
GeneralRe: Good PinmemberMarco Manso5:17 12 May '10  
GeneralRe: Good PinmvpLuc Pattyn5:26 12 May '10  
GeneralMy vote of 1 PinmemberAndyKernahan4:47 11 May '10  
GeneralRe: My vote of 1 Pinmemberjgauffin20:55 24 May '10  
GeneralRe: My vote of 1 PinmemberAndyKernahan3:09 25 May '10  
GeneralRe: My vote of 1 Pinmemberjgauffin3:47 25 May '10  
GeneralRe: My vote of 1 PinmemberAndyKernahan4:00 25 May '10  
GeneralRe: My vote of 1 PinmemberAjay Vijayvargiya16:59 25 May '10  
GeneralRe: My vote of 1 PinmemberAndyKernahan20:44 25 May '10  
GeneralRe: My vote of 1 PinmemberMarco Manso22:54 25 May '10  
GeneralGoal is keep it REALLY simple - yet effective PinmemberMarco Manso12:17 10 May '10  
GeneralUse NLog! PinmemberAlexCode8:49 10 May '10  
GeneralGood enough Pinmembermidascheck5:01 10 May '10  
GeneralSuggestion PinmemberSky Sanders4:20 10 May '10  

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.

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