Pages

Men

rh

4/14/2014

How to create a Log File in asp.net with C#

We need to add this code in Class file. Suppose the class file name is CommonFunctions.cs

 public void CreateLogFiles()
        {
            //sLogFormat used to create log files format :
            // dd/mm/yyyy hh:mm:ss AM/PM ==> Log Message
            sLogFormat = DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + " ==> ";

            //this variable used to create log filename format "
            //for example filename : ErrorLogYYYYMMDD
            string sYear = DateTime.Now.Year.ToString();
            string sMonth = DateTime.Now.Month.ToString();
            string sDay = DateTime.Now.Day.ToString();
            sErrorTime = sYear + sMonth + sDay;
        }



  public void ErrorLog(string sPathName, string sErrMsg)
        {
            StreamWriter sw = new StreamWriter(sPathName + sErrorTime, true);
            sw.WriteLine(sLogFormat + sErrMsg);
            sw.Flush();
            sw.Close();
        }


In C#, we have to call the above code in the below format.

CommonFunctions objCmn = new CommonFunctions();  

public DataSet GetLoginInfo(String strUserName, String strPassword, String strIPAddress,String strBrowserName)
        {
            DataSet dsLogin = new DataSet();
            try
            {
           // some code


            }
            catch(Exception ex)
            {
                objCmn.CreateLogFiles();
                objCmn.ErrorLog(HttpContext.Current.Server.MapPath("~/Logs/ErrorLog"), ex.Message);
                dsLogin = null;
                return dsLogin;
            }
        }



Create one folder in SOLUTION EXPLORER f asp.net application.   The Name of the folder is Called
Logs
Add one text file in Logs folder. The text file name must be  ErrorLog.txt.

No comments :

Post a Comment