Monday, 28 January 2013

Error log into a text file in C#



using System.IO;

/// <summary>
/// Writes text into a Log file under specified path
/// </summary>
/// <param name="text">Error String</param>
/// <param name="directryPath">Relative directry Path, use Server.MapPath() method to get a path</param>
public static void WriteLog(string text, string directryPath)
{
string FileName = string.Empty;
       string FilePath = string.Empty;
       try
       {              
              if (!Directory.Exists(directryPath))
              {
                    Directory.CreateDirectory(directryPath);
              }
              
              //Make a valid file Name
              FileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString();
                
              //Make a FilePath
              FilePath = Path.Combine(directryPath, FileName) + ".txt";
              
              //If file exists then append the text , otherwise create a file and insert the text
              if (File.Exists(FilePath))
              {
                    WriteLogInLogFile(FilePath, text);
              }
              else
              {
                    File.WriteAllText(FilePath, " ");
                    WriteLogInLogFile(FilePath, text);
              }
}
       catch (Exception)
       {               
}          
}


/// <summary>
/// Used to insert the errorLog in text file
/// </summary>
/// <param name="FilePath">File path with directory</param>
/// <param name="ErrorString">Error String</param>
private static void WriteLogInLogFile(string FilePath, string ErrorString)
{
StreamWriter writer;
       try
       {
              writer = new StreamWriter(FilePath, true);
              ErrorString = DateTime.Now.ToString() + " >> " + ErrorString;
              ErrorString += System.Environment.NewLine;
              writer.WriteLine(ErrorString);
              writer.Flush();
              writer.Dispose();
       }
       catch (Exception)
       {
       }
}

Output:
Create a file named “2013125.txt”, and its context will like below:

1/25/2013 3:05:25 PM >> System.Threading.ThreadAbortException: Thread was being aborted.
   at System.Threading.Thread.AbortInternal()
   at System.Threading.Thread.Abort(Object stateInfo)
   at System.Web.HttpResponse.End()
   at System.Web.HttpResponse.Redirect(String url, Boolean endResponse)
   at System.Web.HttpResponse.Redirect(String url)
   at LoginPakistanPolio.btnLogin_Click(Object sender, EventArgs e) in c:\-- Projects --\TestProject\ TestProject \Home.aspx.cs:line 199

No comments:

Post a Comment