C# Class to handle logging to the filesystem

This handy little class will store a text logfile in the /logs directory of your website. You will need to ensure the webserver user has write access to this directory.


using System;
using System.Configuration;
using System.IO;

/// <summary>
/// Summary description for ErrorLogging
/// </summary>
public class ErrorLog
{
  public static void LogError(string logFile, string title, string error)
  {
    LogError(logFile, title, error, false);
  }

  public static void LogError(string logFile, string title, string error, bool lineBreaksBetweenEntries)
  {
    string errorMsg;

    if (lineBreaksBetweenEntries) {
      errorMsg = "---- " + System.DateTime.Now.ToString() + ": " + title + " -----------------" + "\n";
      errorMsg += error + "\n";
    }
    else {
      errorMsg = System.DateTime.Now.ToString() + ": " + title + " => " + error + "\n";
    }

    string fileName = System.Web.HttpContext.Current.Server.MapPath("~/") + "\\Logs\\" + logFile + ".log";
    File.AppendAllText(fileName, errorMsg); // Used for appending log
    // File.WriteAllText(fileName, errorMsg); // Used for overwriting log

  }
}

Leave a Reply