Gal Ratner
Gal Ratner is a Techie who lives and works in Los Angeles CA and Austin TX. Follow galratner on Twitter Google
A simple fast configuration-less rolling file appender

If you ever needed a simple logger and did not want to deal with the complexity of configurating Log4net or the enterprise library you might find this class useful. This is a single class, single file rolling file appender.

Usage:

To use this logger all you need to do is either add the class to your code or use the DLL as a reference. If you chose to use the dll you need to import it in your code as follows:

using InvertedSoftware.PLogger.Provider;


Then to write a log line you simply need to call:

RollingLogProvider.Instance.Log("Default Message");

 
Default values: by default, the logger will write a file named rolling.log and will start a new file every 1MB of data. The file will be placed in the current working directory.

Optional configuration values:

<appSettings>
    <add key="PLogEnabled" value="true"/>
    <add key="PLogFileName" value="bin\log.log"/>
    <add key="PLogFileMaxSizeKB" value="1024"/>
    <add key="PLogFileMessageTemplate" value="{0} This is the default message template {1}"/>
    <add key="PLogLevel" value="4"/>
  </appSettings>

If you choose to add a message template you can call it in the following format:

RollingLogProvider.Instance.Log(string.Empty, true, 0, nullnew string[] { DateTime.Now.ToShortDateString(), "End of message" });

You can also log exceptions

RollingLogProvider.Instance.Log(string.Empty, false, 4, new Exception("test exception"new Exception("inner exception")), new string[] { DateTime.Now.ToShortDateString() });

Performance


I have tested the logger twice, once with a default message and once with a template message using the following code:

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();

for (int i = 0; i < 1000000; i++)
{
     RollingLogProvider.Instance.Log("Default Message");
     RollingLogProvider.Instance.Log(string.Empty, true, 0, nullnew string[] { DateTime.Now.ToShortDateString(), "End of message" });
}
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;


I got back 321 milliseconds for 1,000,000 messages and 4.76 seconds for 1,000,000 template messages. In all fairness if you look at the code, you will notice it is using a Task to write to the log file so calling Log will return before the message was actually written to the disk, however, using this method still speeds up your system significantly.
I have attached both the source code and the compiled DLL to the zip file below and would love to hear feedback from users.

Update: I have placed the code in codeplex and will be maintaining it there.

Shout it


Posted 13 Feb 2011 3:45 AM by Gal Ratner
Filed under: , ,
Attachment: PLogger.zip

Powered by Community Server (Non-Commercial Edition), by Telligent Systems