|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
Picture 1. Sample error message
Picture 2. Sample error log file OverviewThis article demonstrates how to create a simple text based log file to log error messages with your own format using a C# class. Based on your needs, this class can modified and edited to create other log files, such as user activity log, user login time log, etc. This class demonstrates the use of following namespaces:
The namespaces contain methods to create files in directories. Installation StepIf you have downloaded the source code, you can follow these steps to install the project. You can then build and debug the code with VS.NET.
Source CodeIn this project, the main idea is to create a class, using System.IO;
using System.Text;
Before we make a private string sLogFormat;
private string sErrorTime;
public 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;
}
and this is a public void ErrorLog(string sPathName, string sErrMsg)
{
StreamWriter sw = new StreamWriter(sPathName+sErrorTime,true);
sw.WriteLine(sLogFormat + sErrMsg);
sw.Flush();
sw.Close();
}
To use this class, I create an example web form called: This is the code behind for this page. I call the private void BtnFind_Click(object sender, System.EventArgs e)
{
try
{
StreamReader sr = new StreamReader(this.TxtFilename.Text);
sr.Read();
sr.Close();
Msg.Visible = true;
Msg.Text = "File "+ this.TxtFilename.Text +" was found";
}
catch(Exception ex)
{
CreateLogFiles Err = new CreateLogFiles();
Err.ErrorLog(Server.MapPath("Logs/ErrorLog"),ex.Message);
Msg.Visible = true;
Msg.Text = "Fatal error : "+ ex.Message + ", please find a complete error at ErrorLog file";
}
}
I am using That's it. :-) You can view complete source code in the download file.
|
||||||||||||||||||||||