I have written an automation program with a start and a stop button, that does various tasks over and over, until user clicks stop. In the program I have several Console.WriteLines that shows the outcome of each little sub-task. I have decided to convert these to a .txt log, so i can review after shutting down the program, or in case it crashes.
I made the following Logger class:
class Logger
{
private string _logName;
public Logger(string logName)
{
_logName = logName;
using (StreamWriter w = File.AppendText(_logName + ".txt"))
{
w.WriteLine("-------------------------------");
}
}
public void Log(string logMessage)
{
using (StreamWriter w = File.AppendText(_logName + ".txt"))
{
w.WriteLine(DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + " " + logMessage);
}
Console.WriteLine(logMessage);
}
}
The question: In another class i have a Logger instance called _logger. I call _logger.Log over and over, each time I want to write a line to the log. Sometimes that goes very quickly after each other. It feels wrong to create a new instance of StreamWriter every time I write a line to the log (in the using statement). I therefore thought of putting the instantiation of StreamWriter in the constructor, but that breaks the cleanup features of the using statement, does it not?
Any idea how best to do this?
Thanks in advance.