In this post, I will show you how to write an error log files by using a class file (.cs).
First of all, a class called CreateLogFiles needs to be created. In this class file, add in the codes as following:
using System;In your own web page, you can use this class to create error log files, namely whenever an exception is being caught, it will create an error log file with the exception error message.
using System.IO;
using System.Text;
namespace CSharpWeb
{
public class CreateLogFiles
{
private string sFormat;
private string sTime;
public CreateLogFiles()
{
sFormat = DateTime.Now.ToShortDateString().ToString()+" "+DateTime.Now.ToLongTimeString().ToString()+" --- ";
sTime = DateTime.Now.ToString("yyyyMMdd");
}
public void CreateErrorLog(string strPath, string sErr)
{
StreamWriter sw = new StreamWriter(strPath+sTime+".txt",true);
sw.WriteLine(sFormat + sErr);
sw.Flush();
sw.Close();
}
}
}
The code below is an example of mine, which I will call the CreateErrorLog function when a Checking button is clicked.
private void btnCheck_Click(object sender, System.EventArgs e)Fro the codes as above, I am using Try…Catch method. Whenever an exception occurs, it will get caught by the Exception method. In there, an error log files will be created and saved as a keep track.
{
try
{
// ...The rest of your codes here
}
catch(Exception ex)
{
CreateLogFiles Error = new CreateLogFiles();
Error.CreateErrorLog(Server.MapPath("Logs/ErrorLog"), ex.Message);
}
}
That’s it. If you have any curious feel free to ask me. Cheers!
4 comments:
Hi, what is Map Path in "Error.CreateErrorLog(Server.MapPath("Logs/ErrorLog"), ex.Message)"?
Can I create our own path for error log?
Can I update this error log? So that every time an error has occur, this error log will be updated. Is this possible?
Thank you. :)
Server.MapPath function converts a virtual path into its corresponding physical path and is typically used to read or modify physical files on the server in the context of a Web request.
Sure. You can create your own path for this error log.
And yes again, you can update this error log whenever an error has occur, as the main purpose that i want to show you in this post is to keep track of the occurred exception and update to the error log.
thank you yar.............
its best code..
solve my many problems
thanx its solve my many problem...
Post a Comment