How to write error log in ASP.NET and C#
The below code will help you to capture error log information in the text file format. In the exception part pass the error message to ErrorLog function. In the errorlog method will capture the error information as a log file.
// ASP.NET Error
Log
using System.IO;
public void Log(string
sMessage)
{
StreamWriter
objSw = null;
try
{
string
sFolderName = Server.MapPath(@"\Logs\");
if
(!Directory.Exists(sFolderName))
Directory.CreateDirectory(sFolderName);
string
sFilePath = sFolderName + "Transaction.log";
objSw = new StreamWriter(sFilePath, true);
objSw.WriteLine(DateTime.Now.ToString() + "
" + sMessage + Environment.NewLine);
}
catch
(Exception ex)
{
// Log("Error
-" + ex.Message);
}
finally
{
if
(objSw != null)
{
objSw.Flush();
objSw.Dispose();
}
}
}
//Windows application Error Log
using System.IO;
public static void ErrorLog(string sMessage)
{
StreamWriter objSw = null;
try
{
string sFolderName = Application.StartupPath + @"\Logs\";
if (!Directory.Exists(sFolderName))
Directory.CreateDirectory(sFolderName);
string sFilePath = sFolderName + "Error.log";
objSw = new StreamWriter(sFilePath, true);
objSw.WriteLine(DateTime.Now.ToString() + " " + sMessage + Environment.NewLine);
}
catch (Exception ex)
{
// Comman.ErrorLog("Error -" + ex.Message);
}
finally
{
if (objSw != null)
{
objSw.Flush();
objSw.Dispose();
}
}
}
1 comment:
A bit late to comment, but I just stumbled on this now.
It's a nice logging routine, but isn't the recursive call dangerous if there's an error? If an exception is being thrown from the try block, it might end up calling itself over and over again...
Post a Comment