Reputation:
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
Reputation: 21878
To answer your question in comment: Why is it recommended to use one of these (Log4Net, NLog) instead?
BTW, my +1 goes to NLog.
Upvotes: 1
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