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

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

Rate This
  • Comments 12

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]

Leave a Comment
  • Please add 4 and 3 and type the answer here:
  • Post
  • 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.
  • 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.
  • 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!
  • PingBack from http://elevate.wordpress.com/2006/09/25/solutions-for-basic-logging/
  • 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

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

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

  • private static readonly string LOG_FILENAME = Path.GetTempPath() + "My Log File.txt";

    public static void LogMessageToFile(string msg)

    {

       msg = string.Format("{0:G}: {1}\r\n", DateTime.Now, msg);

       File.AppendAllText(LOG_FILENAME, msg);

    }

  • Thanks for this, it is very helpful.

    Simple, elegant just what I wanted.

    I will keep this as the basis for my future loggers.

  • Even better...

    private static readonly string LOG_FILENAME = Path.GetTempPath() + "My Log File.txt";

    public static void LogMessageToFile(string msg)

    {

      msg = string.Format("{0:G}: {1}{2}", DateTime.Now, msg, Environment.NewLine);

      File.AppendAllText(LOG_FILENAME, msg);

    }

  • Sometimes..okay most of the time....simple is better.  Thanks Jani!

  • thank you, really useful stuff. I'll change the log path with my app path though, it makes more sense to me.

Page 1 of 1 (12 items)