Reputation: 2956
I am just wondering on a good way to write to log.
I've created a singleton class Logger which has 2 methods: Write(eventDate, messageType, message)
and Dispose().
In constructor I create StreamWriter
(with AutoFlush set to true) which is used to append lines in a Write method. Logging is used extensively (but in one thread), about 10-15 records per second.
Now I reflect on the following two questions, comments on which I expect from you :)
First is autoflushing - does it open and close file all the time? Is File.AppendText
similar?
Second, in Dispose I flush StreamWriter
and then call Dispose on it. What if Dispose isn't called? How can I make sure it will be disposed of? Because if I remove AutoFlush and will flush the stream time to time (may be by maintaining inner counter) and when n records are written to buffer, I'd flush it, but what if less than n records are written and program terminates?
Upvotes: 3
Views: 4934
Reputation: 114956
Is there any reason you can't use an open source logging framework such as NLog?
It's pretty easy to set up to write to a file
Here is a really easy way to write your first logs to a file:
Open the automatically created NLog.config file and uncomment the sample target and rule, they should look like so:
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
<logger name="*" minlevel="Trace" writeTo="f" />
var logger = NLog.LogManager.GetLogger("SampleLogger");
logger.Trace("Logged Trace");
logger.Debug("Logged Debug");
logger.Info("Logged Info");
logger.Warn("Logged Warn");
logger.Error("Logged Error");
logger.Fatal("Logged Fatal");
you'll get this log file
Upvotes: 5
Reputation: 121869
Open/code automatically "flushes" ... but Autoflush doesn't "close/open".
In theory, you don't even need "Dispose" (this is managed code, after all). You do need to call "Close()" somewhere.
If the program closes gracefully, it should automagically flush and close - all your data should be written.
If the program terminates abnormally - all bets are off as to what will or won't happen. All you know is that your resources will be freed - but your data may or may not be written (and the data file may or may not be corrupted).
'Hope that helps...
Upvotes: 1