How can I easily log a message to a file for debugging purposes?

Published 27 March 06 06:59 PM

Often, you need a way to monitor your applications once they are running on the server or even at the customer site -- away from your Visual Studio debugger. In those situations, it is often helpful to have a simple routine that you can use to log messages to a text file for later analysis.

Here’s a simple routine that has helped me a lot for example when writing server applications without an user interface:

using System.IO;
        
public string GetTempPath()
{
    string path = System.Environment.GetEnvironmentVariable("TEMP");
    if (!path.EndsWith("\\")) path += "\\";
    return path;
}

public void LogMessageToFile(string msg)
{
    System.IO.StreamWriter sw = System.IO.File.AppendText(
        GetTempPath() + "My Log File.txt");
    try
    {
        string logLine = System.String.Format(
            "{0:G}: {1}.", System.DateTime.Now, msg);
        sw.WriteLine(logLine);
    }
    finally
    {
        sw.Close();
    }
}

With this simple method, all you need to do is to pass in a string like this:

LogMessageToFile("Hello, World");

The current date and time are automatically inserted to the log file along with your message.

[author: Jani Järvinen, C# MVP]

Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Paul Fullhouse said on March 28, 2006 11:42 AM:
Shouldn't you be recommending people use the Event Log for this purpose?  Developers should create an event message source and use the application log or create a custom event log.  Our applications typically implement the System.Configuration.Install.Installer interface in order to add the source to the log.
# Doogal said on March 30, 2006 11:39 AM:
I've always liked the TraceListener infrastructure, since you can turn them on or off and you can redirect them to the Event Log, text file, debugger output etc. And you can write your own trace listener to log to whatever you like.
# Jani Järvinen said on April 4, 2006 12:42 AM:
Paul, Doogal: Thank you for your comments. Indeed, there are many ways to support logging in .NET applications, trace listeners and the Windows Event Log being two choices. This FAQ entry was not meant to answer the question, “Which logging method should I choose for my application?”

Instead, I wanted to show with a simple and short example of functionality that is often asked by beginning programmers. I also prefer trace listeners, but sometimes one just needs something very simple. As for the Event Log, that is one choice, but often debugging events are highly frequent and verbose, and thus unsuitable to be added to the Event Log.

I’m working on further FAQ entries relating debugging, so stay tuned for a more complete picture of logging tips. Thanks!
# Solutions for basic logging « # cat blogPosts said on September 24, 2006 11:14 PM:
PingBack from http://elevate.wordpress.com/2006/09/25/solutions-for-basic-logging/
# Everyone should have at least one Gotchi! said on May 8, 2007 3:42 AM:

Der einfachste Weg, meiner Meinung nach, um ein LogFile für ein Applikation in C# zu erstellen: public static void Log(String logMessage) { using (StreamWriter w = File.AppendText("log.txt")) { w.Write("\r\n{0} {1}&qu

# Everyone should have at least one Gotchi! » LogFiles in C# erstellen said on July 18, 2007 1:25 PM:

PingBack from http://blog.gotchi.at/2007/05/08/logfiles-in-c-erstellen/

# Honest Illusion said on April 16, 2008 10:07 AM:

Today, either Bloglines.com or blogs.MSDN.com blinked, and suddenly I'm seeing old entries on the 'C#

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

This Blog

Syndication

Page view tracker