Logging a message to a file for debugging purposes using C#.

There are any number of times where I find myself puzzled over a problem that exists on a remote server and cannot be reproduced on my local development box. There are different ways to solve this, but sometimes it’s just helpful to have a way to log messages to a file. This last incident involved OpenLDAP and it returning different types from a search of attributes depending on which box I was running it on.

Blatantly stolen from here.

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();
    }
}

One Comment

  1. I would suggest using either NLog, Log4net or EntLib.Logging for this. Especially NLog, it is not that much more work to configure. You get the flexibility of where to send the log entries, formatting the layout and categorizing each log entry. Sprinking calls to LogMessgeToFile() all over your code means when it comes time to deploy, you may need remove some un-necessary calls because they may not be appropriate in a production environment.

Leave a Reply

Your email address will not be published. Required fields are marked *