Create a custom debug log file in an ASP.Net Class

This is a quick example of how to create a custom debug log file in an ASP.Net class which you can use in your website.  If the file doesn’t exist, it creates it.  It names the file today’s date.  And records a date/time at the start of each log entry

.aspx.cs page

...
CustomDebug.WriteToLog("Blah Blah Blah...");
....

 

.cs class

using System;
using System.Web;
using System.IO;
using System.Globalization;


public class CustomDebug
{
	public CustomDebug()
	{
		//
		// TODO: Add constructor logic here
		//
	}

        public static void WriteToLog(string errorMessage)
        {
            try
            {
                string path = "E:\\Logs\\CustomDebug\\" + DateTime.Today.ToString("dd-MM-yy") + ".txt";
                if (!File.Exists(path))
                {
                    File.Create(path).Close();
                }
                using (StreamWriter w = File.AppendText(path))
                {             
                    w.WriteLine(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss") + ": Debug Message: " + errorMessage);
                    w.Flush();
                    w.Close();
                }
            }
            catch (Exception ex)
            { //handle exception
            }
        }
}