ASP.NET Simple error logger

ErrorLogging class

using System;using System.Web;using System.Collections;using System.Collections.Generic;using System.Data;using System.Diagnostics;public class ErrorLogging{    public void WriteError(string ErrorMessage, string RequestPath)    {        try        {            if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("/log/")))            {                System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("/log/"));            }            string LogName = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + ".txt";            System.IO.StreamWriter sw = new System.IO.StreamWriter(System.Web.HttpContext.Current.Server.MapPath("~/log/" + LogName), true);            sw.WriteLine(DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + " ==> " + RequestPath + " ==> " + ErrorMessage);            sw.Flush();            sw.Close();        }        catch        {        }    }}

Usage

Global.asax -> Application_Error method

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Security;using System.Web.SessionState;namespace Harlequin{    public class Global : System.Web.HttpApplication    {        protected void Application_Start(object sender, EventArgs e)        {        }        protected void Session_Start(object sender, EventArgs e)        {        }        protected void Application_BeginRequest(object sender, EventArgs e)        {        }        protected void Application_AuthenticateRequest(object sender, EventArgs e)        {        }        protected void Application_Error(object sender, EventArgs e)        {            try            {                Exception currentException = Server.GetLastError();                ErrorLogging ErrorLog = new ErrorLogging();                ErrorLog.WriteError(currentException.GetBaseException().Message + " TRACE: " + currentException.GetBaseException().StackTrace, Request.RawUrl);            }            catch             { }        }        protected void Session_End(object sender, EventArgs e)        {        }        protected void Application_End(object sender, EventArgs e)        {        }    }}

Leave a Reply

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