Create A Logging Function In A C# Singleton

Create A Logging Function In A C# Singleton

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))

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.

Check out some of my software

eSource Development – Your partner in creating world class websites and software

Source For Reference

Professional Test Driven Development with C#: Developing Real World Applications with TDD
Amazon Price: $23.94
List Price: $44.99
Windows 8 Apps with XAML and C# Unleashed
Amazon Price: $27.45
List Price: $49.99
Agile Principles, Patterns, and Practices in C#
Amazon Price: $33.00
List Price: $69.99
Professional Test Driven Development with C#: Developing Real World Applications with TDD
Amazon Price: $44.99