Implement Logger in asp.net

First of create LoggingConstant.cs File in that Declare all Pages name as variable without extension.
For ex.
public enum ModuleToLog
{
default,
login
}
public enum LogType
{
DEBUG,
EXCEPTION,
INFO
}

After that create Logger.cs File..

public class Logger
{
public static void Write(LogType eLogType, ModuleToLog eModule, string strMethodName, string LogMessage, string strUserId)
{

string LogFilePath = System.Web.HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath + “/Logs”);

//Create directory for Year/Month/
LogFilePath = string.Format(“{0}/{1}/{2}”, LogFilePath, DateTime.Now.Year.ToString(), DateTime.Now.ToString(“MMM”));
DirectoryInfo ObjDirectoryInfo = new DirectoryInfo(LogFilePath);
//string strLogFile = string.Format(“{0}/{1}.log”, LogFilePath, DateTime.Now.ToString(“dd-MMM-yyyy”));

string strLogFile = string.Format(“{0}/{1}.log”, LogFilePath, strUserId + “_” + DateTime.Now.ToString(“ddMMMyyyy”));
try
{
if (ObjDirectoryInfo.Exists == false)
{
ObjDirectoryInfo.Create();
}

StreamWriter sw = new StreamWriter(strLogFile, true);

sw.WriteLine(string.Format(“[{0}][{1}][{2}][{3}][{4}] {5}”, DateTime.Now.ToString(), eLogType.ToString(), eModule.ToString(), strMethodName, strUserId, LogMessage));
sw.Close();
sw.Dispose();
}
catch (Exception ex)
{

}
}
}

——–call this function —
try
{
Logger.Write(LogType.INFO, ModuleToLog.Default, “btnSave_Click”, “Write Comments”, loggedinUserName);

}
catch (Exception ex)
{
Logger.Write(LogType.EXCEPTION, ModuleToLog.WriteBoardBookComments, “btnSave_Click”, ex.StackTrace.ToString() , userdetail.Name);
}

Share