user470760
user470760

Reputation:

.NET Logging Class Doesn't Write

I just wrote a simple logging class for use among various threads, based on examples I found at MSDN and a few other sites. Problem is, it creates the file log file, but never actually writes anything to it (it writes to the console properly though).

public class Logger
{
    private static Logger instance;
    private Logger() { }
    private static StreamWriter writer;

    public static Logger GetInstance()
    {
        lock (typeof(Logger))
        {
            if (instance == null)
            {
                instance = new Logger();
            }

            return instance;
        }
    }

    public void OpenFile(String file)
    {
        // Open log file for writing and append to it
        writer = new StreamWriter(file, true);
    }

    public void LogMessage(String message)
    {
        string dt = DateTime.Now.ToString("yyyy-MM-dd H:mm:ss :: ");

        writer.WriteLine(dt + message);
        Console.WriteLine(dt + message);
    }

    public void LogError(String error)
    {
        string dt = DateTime.Now.ToString("yyyy-MM-dd H:mm:ss :: ");

        writer.WriteLine(dt + "ERROR: " + error);
        Console.WriteLine(dt + "ERROR: " + error);
    }
}

and I am doing the following in my Program.

static void Main(string[] args)
{
    Logger log = Logger.GetInstance();
    log.OpenFile("app.log");

    log.LogMessage("Starting App...");

Upvotes: 2

Views: 611

Answers (2)

Serge Wautier
Serge Wautier

Reputation: 21878

To answer your question in comment: Why is it recommended to use one of these (Log4Net, NLog) instead?

  • Because it's already debugged.
  • Because you avoid nasty bugs such as the multithreading write access pointed to by Jalaal.
  • Because the day your logging needs change (or you want to get rid of logging!), you don't even need to recompile your program: It's simply a matter of configuration in your app.config.
  • Because once you have learned to use such a logging framework, you'll be able to re-use it very easily in other projects or contexts, which may have more advanced requirements.
  • Because once you realize how powerful yet easy to use they are, you may want to add more powerful logging without the need to program it.

BTW, my +1 goes to NLog.

Upvotes: 1

Jalal Said
Jalal Said

Reputation: 16162

writer.WriteLine(dt + message);
writer.Flush();

or when you declared the writer set AutoFlush to true:

writer = new StreamWriter(file, true);
writer.AutoFlush = true;

Edit: Also since your class will access from multi-thread so you should use lock before writing to the stream because the StreamWriter instance is not thread safe, so:

private readonly object _writerLocker = new object();

lock (_writerLocker)
{
    writer.WriteLine(dt + "ERROR: " + error);
}

Upvotes: 2

Related Questions