Flag This Hub

Create A Logging Function In A C# Singleton

By


How to write a logging function for your C# software

I have used the singleton design pattern for many years. It comes in handy for so many things, most especially for logging functions. A singleton is a class which can only be instantiated once, thus using it to hold a globally accessible logging function makes sense.

To accomplish this, you start by creating a class in Visual Studio that will contain all of your singleton code.

Creating the singleton class

public class MyEnvironment
{
    private static MyEnvironment instance = null;
    private static string sLogFilePath;

    protected MyEnvironment()
    {
        sLogFilePath = Application.StartupPath.ToString();
    }

    public static MyEnvironment Instance()
    {
        if (instance == null)
        {
            instance = new MyEnvironment();
        }
        return instance;
    }

Notice that there is a variable in the code called sLogFilePath. This will hold the path where our log files will be written. By default it is assigned the directory in which the application was started. You can add additional paths if a directory other than the application root is needed, or you can create a simple assignment call that allows your application to set the log file directory on the fly. This is great if your application allows the users to change these directories.

public SetLoggingDir
{
	set { sLogFilePath = value; }
}

From here, we now create the WriteToLog function. This function will act as the global logging function for any and all classes in our current project. The way it's written here, the logs run for a day as indicated by the filename. This allows you to delete old logs after a period of time.

    public void WriteToLog(string sText)
    {
        DateTime dtNow = DateTime.Now;
        StreamWriter myStream = null;
        sText = dtNow.ToShortDateString() + " " +
        dtNow.ToShortTimeString() + ": " + sText;
        string sLogFilename = sLogFilePath + "\\" +
        string.Format("{0:D2}{1:D2}{2:D2}MyApp.log", (dtNow.Year-2000), dtNow.Month, dtNow.Day);
        using (myStream = new StreamWriter(sLogFilename, true))
        {
            myStream.WriteLine(sText);
        }
    }

The function takes the message to be logged as the argument. The function then creates a string that is date / time stamped followed by the message. To call the WriteToLog function, simply use:

MyEnvironment.Instance().WriteToLog("Application message test");

 

This canned function embedded within a singleton makes this some of the most re-usable code I have. Hope this helps you out.

Source For Reference

Effective C#  (Covers C# 4.0): 50 Specific Ways to Improve Your C# (2nd Edition) (Effective Software Development Series)
Amazon Price: $20.74
List Price: $39.99
Professional Cross-Platform Mobile Development in C#
Amazon Price: $23.07
List Price: $44.99
Modern Software Development Using C# .NET
Amazon Price: $41.10
List Price: $142.95
Agile Principles, Patterns, and Practices in C#
Amazon Price: $50.23
List Price: $69.99

Comments

Michael Wittmann 17 months ago

Thanks, i could make use of it, with some changes. There is a bug, with SetLoggingDir (string is missing).

AlanSchneider 15 months ago

D'oh! Sorry about that... good catch. I have so many version so of this code and I think I did that part "on the fly."

Thanks for the heads up.

Jonas 13 months ago

How does this stands in terms of thread-safe? http://www.yoda.arachsys.com/csharp/singleton.html

Submit a Comment
Members and Guests

Sign in or sign up and post using a hubpages account.



    Like this Hub?
    Please wait working