Monday, 20 September 2021

Generate Log File in C#

 

Generate Log File in C#

This article demonstrates how to create a simple text based log file to log error messages with your own format using a C# class.

Create a Class Name as LogFileGeneration

using System.IO;
using System.Text;

private string sLogFormat;
private string sErrorTime;

public LogFileGeneration ()
{
//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();
}

Now you can use this ErrorLog method to log the Error Code.

ErrorLog(@”D:\log.txt”,”Message”)

No comments:

Post a Comment