Monday, 19 December 2011

C# How To: Log to File

Over the past few weeks, I've needed to write a number of small "throw-away" console applications. These applications processed a large amount of data and there was a need to log progress. I wrote the following fairly reusable file logging class which someone may find useful. Alternatively, I'm also interested to get some feedback on whether it could be improved in any way, so feel free to comment on this one.

public class FileLogger
{
    private static FileLogger singleton;
    private StreamWriter logWriter;

    public static FileLogger Instance
    {
        get { return singleton ?? (singleton = new FileLogger()); }
    }

    public void Open(string filePath, bool append)
    {
        if (logWriter != null)
            throw new InvalidOperationException(
                "Logger is already open");

        logWriter = new StreamWriter(filePath, append);
        logWriter.AutoFlush = true;
    }

    public void Close()
    {
        if (logWriter != null)
        {
            logWriter.Close();
            logWriter = null;
        }
    }

    public void CreateEntry(string entry)
    {
        if (this.logWriter == null)
            throw new InvalidOperationException(
                "Logger is not open");
        logWriter.WriteLine("{0} - {1}",
             DateTime.Now.ToString("ddMMyyyy hh:mm:ss"),
             entry);
    }
}
Simple example of usage (I'd wrap this in a try/catch/finally where the finally calls the close method):

FileLogger.Instance.Open(@"C:\MyLog.log", false);
FileLogger.Instance.CreateEntry("Hello, world!");
FileLogger.Instance.Close();