Simplest Logger for .Net?

If you need to supply logging functionality for your application, you most likely use well known logging frameworks such as log4net or the Logging Application Block from Microsoft’s Enterprise Library.

But logging frameworks may be overkill if you just need to trace a couple of output lines while debugging on your development machine, and a simple procedure might be sufficient:

void Log(string s)
{
  System.IO.File.AppendAllText(@"c:\path\to\my.log", 
    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " +
    s + "\r\n");
}

Whether you implement this procedure as private or as (static) public is up to your use case.

A little extension even supports indentation:

int indent = 0;
void Indent() { indent += 2; }
void Unindent() { indent -= 2; }

void Log(string s)
{
  System.IO.File.AppendAllText(@"c:\path\to\my.log",
    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " +
    new string(' ', indent) +
    s + "\r\n");
}

void StartLog(string s)
{
  Log("Start:" + s);
  Indent();
}

void EndLog(string s)
{
  Unindent();
  Log("End:" + s);
}

 

One Response to Simplest Logger for .Net?

  1. Michael says:

    Most logging frameworks are overkill. However, not all of them are. Read this.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: