Search My Warehouse

2010-05-20

Error log in ASP.net c#

Just put log.cs in appcode, create a folder in application root named ‘Logs’

log.cs

using System;
using System.Configuration;
using System.Data;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

///


/// Summary description for Log
///

public class Log
{
#region Methods

public void WritetoLog(string strModule, string strRemarks)
{
// sLogDateFormat: take current date and time

string sLogDateFormat = DateTime.Now.ToString(“dd/MM/yyyy”) + ” ” + DateTime.Now.ToString(“HH:mm:ss”);

// sLogFileName: log file name for the module – user login with month and year

string sLogFileName = @”Error_Log_” + DateTime.Now.ToString(“MMMMyy”) + “.txt”;

// sLogFilePath: virtual path for storing the log file

string sLogFilePath = @”Logs/” + DateTime.Now.Year.ToString() + “/” + DateTime.Now.ToString(“MMMMyy”);

// check for existance of virtual path, if not create the pathin YYYY/MonthNameYYYY format, ex:- Logs/2008/July2008/

if (!Directory.Exists(sLogFilePath))
{

Directory.CreateDirectory(HttpContext.Current.Server.MapPath(sLogFilePath));

}

// open streamwriter to check existance of log filename, if notcreate the log file

StreamWriter sw;

if (!File.Exists(HttpContext.Current.Server.MapPath(sLogFilePath + “/” + sLogFileName)))
{

sw = File.CreateText(HttpContext.Current.Server.MapPath(sLogFilePath + “/” + sLogFileName));

sw.Flush(); // Flush the streamwriter object

sw.Close(); // Close the streamwriter object

sw = null;

}

//open streamwriter object to open the log file and appendremarls

StreamWriter writer = new StreamWriter(HttpContext.Current.Server.MapPath(sLogFilePath) + “/” + sLogFileName, true);

writer.WriteLine(sLogDateFormat + ” :| : ” + strModule + ” :| : ” + strRemarks); // write current date & remarks

writer.Close(); //close the streamwriter

writer = null;
}

#endregion Methods

}

.aspx.cs

try
{

//Your Function

}

catch (Exception ex)

{

StackFrame stackFrame = new StackFrame(0, true);
objLog.WritetoLog(stackFrame.GetFileName() + “_” + stackFrame.GetMethod().Name, ex.Message.ToString());

}

Feed