Search

Log messages to a file

This C# code snippet logs messages to a disk file for debugging or other logging purposes. Such code is especially useful when writing server applications which contain no user interface. Call the following simple method like:
LogMessageToFile ("Message to be logged.");
Automatically, the current datetime is inserted with your message into the log file.
using System; 
using System.IO; 
 
public string GetTempPath()
{
   string path = 
      System.Environment.GetEnvironmentVariable ("TEMP");
   if (!path.EndsWith ("\\"))
   {
      path += "\\";
   }
   return path;
}
 
public void LogMessageToFile (string message)
{
   System.IO.StreamWriter sw = 
      System.IO.File.AppendText(
         GetTempPath() + "Logfile.txt"); // Change filename
   try
   {
      string logLine = 
         System.String.Format(
            "{0:G}: {1}.", System.DateTime.Now, message);
      sw.WriteLine(logLine);
   }
   finally
   {
      sw.Close();
   }
}
More sophisticated logging can be achieved using the Windows Event Log. Simply, create an event message source and either create a custom event log or use the application log. Typically, to add a source to the log, such logging programs will implement the System.Configuration.Install.Installer interface.
And, the TraceListener infrastructure can be used to turn them on or off or redirect sources to debugger output, the Event Log, a text file, etc. A custom trace listener can log to an arbitrary log.