Sitemap

Code: Simple singleton logger

3 min readSep 24, 2014

It is possible that during your next interview you will be asked questions about patterns, one of the most popular and easy to implement is Singleton pattern. I do not want to reinvent the wheel, so I won’t tell you theory about it, just google it. I want to tell you a story about how I understood its purpose when I was implementing logging functionality for one tool.

I had one knowledge transfer where I was asked how to implement class that could have only one instance. I didn’t know anything about patterns, but still it was possible to solve the task knowing only basic facts about constructors and static variables. It was hard, and frankly speaking, I didn’t understand the aim and how to solve it. Only when I had task that just encourage me to implement something that was similar to singleton I said “Eureka”.

For those who are lazy bones, I leave here simple example of singleton C# class. You can find more information on MSDN.

using System;

public class Singleton
{
private static Singleton instance; // static!!!
private Singleton() {} // notice that it is private constructor
public static Singleton Instance
{
get
{
if (instance == null) // check if singleton exists
{
instance = new Singleton();
}
return instance;
}
}
}

I used singleton because I needed to log all events in all project files through the solution. I used built in Visual C# class TraceSoure to trace events. Without Singleton I had to add field/property/reference to connect to the source object that was listening for events.

Get Zakhar Berkut’s stories in your inbox

Join Medium for free to get updates from this writer.

Another problem I had to solve was how to combine logging and singleton logic without implementing similar functionality in couple of projects. The answer is also very simple — use inheritance! Example:

using System; 
using System.Diagnostics; // includes TraceSource class
namespace TraceSourceSingleton
{
public class Singleton : TraceSource
{
private static Singleton instance;
// init with the help of TraceSource class as base
private Singleton(string Name): base (Name)
{
// clear list of default listeners
this.Listeners.Clear();
// Text listener for writing into txt log file
// You can listen to Console with ConsoleTraceListener
TextWriterTraceListener txt =
new TextWriterTraceListener(“E: \\ log.txt”);
// Don't forget to add your listeners to trace source!
this.Listeners.Add (txt);
// Without switches TraceSource does not work as expected
this.Switch = new SourceSwitch(“mySwitch”);
// You can filter event types: errors, warnings, etc...
this.Switch.Level = SourceLevels.All;
// This will force to save log result to txt file
Trace.AutoFlush = true;
}
// All configuration can be done in app.config file that
// has xml structure. But I prefer "code" variant.

public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton(“MyApp”);
}
return instance;
}
}
}
}

As you see there more comments than code lines ☺. Last question user may have: “How to use this stuff?” Example:

class Program
{
static void Main(string[] args)
{
// Just information: 2 possible ways to use
Singleton.Instance.TraceInformation(“Information event.”);
Singleton.Instance.TraceEvent(TraceEventType.Information,
0, “Information event.”);
// Critical may be used for example for Exception events
Singleton.Instance.TraceEvent(TraceEventType.Critical,
0, “Critical event”);
}
// All types of events are defined in enum TraceEventType
}

Result in log file:

MyApp Information: 0 : Information event.
MyApp Information: 0 : Information event.
MyApp Critical: 0 : Critical event
Press enter or click to view image in full size

It is my fist story with code sample. So if you’ve skipped all text above or fell asleep, feel free to download sources from my GitHub account: dreamminister.

Zakhar Berkut
Zakhar Berkut

Written by Zakhar Berkut

Stories about being Intern/Junior/Regular C#/C++, Python(Django) developer, code examples, thoughts about life and self-development.