Reputation: 25287
I need to log info to a file around 1000-2000 times a minute. I also need to save that info in case the app crashes.
Currently here's what I'm doing:
using(StreamWriter sw=new StreamWriter(filename,true))
{
sw.WriteLine(info);
}
This works, but it's extremely slow.
I'd like to be doing something like this:
static StreamWriter sw=new StreamWriter(file,true);
....
public static void Main(...)
{
.....
sw.WriteLine(....);
}
but when I write code like this, I'm afraid that the info I store will get lost when the app crashes.
What can I do to preserve info in the file without having to open and close it all the time?
Upvotes: 4
Views: 254
Reputation: 330
I've used this class it implements a queue that is flushed every X message or Y time.
You can improved it moving the using block outside the while in flushLog() and setting a fixed filename
Upvotes: 1
Reputation: 109567
You can call StreamWriter.Flush()
after each write.
public static void Main(...)
{
.....
sw.WriteLine(....);
sw.Flush();
}
But you should use NLog or Log4Net!
Upvotes: 6