Pages

Men

rh

7/21/2014

How to log exception into text file using C# with Asp.net

Create a class file called exceptionLog.cs Add the code.


 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 the application folder create a folder called Logs. And in that folder add a  text file called ErrorLog.

Example how to call these functions.




exceptionLog obj = new exceptionLog();

   public void LogoutInfo(Int64 intLoginID, Int64 intUserrID)
        {
            bool blStatus;
            try
            {
                SqlParameter[] objParam = new SqlParameter[2];
                objParam[0] = new SqlParameter("@LoginID", intLoginID);
                objParam[1] = new SqlParameter("@UserID", intUserrID);
                blStatus = Convert.ToBoolean(SqlHelper.ExecuteNonQuery(Statics.connectionString, System.Data.CommandType.StoredProcedure, "UserLogOutInfo", objParam));
                return blStatus;
            }
            catch (Exception ex)
            {
                obj.CreateLogFiles();
                obj.ErrorLog(HttpContext.Current.Server.MapPath("~/Logs/ErrorLog"), ex.Message);
              
            }
        }







No comments :

Post a Comment