During website development, it will be good, if we write log with either error msg /
information message. Log file can be simple text file. In this log file we can store the information according our requirement. Writing log not only saves our time as well as helps us to track the application behaviour in proper manner.
Please find below the simple C# class which can be called from anywhere by passing the log text.
using System;
using System.IO;
using System.Web;
namespace HimasagarNS
{
///
/// This class used to created log file
///
public class CreateLogFile
{
private string logFormat = string.Empty;
private string logPath = string.Empty;
///
/// Initializes a new instance of the class.
///
/// The log message.
public CreateLogFile(string logMessage)
{
LogWrite(logMessage);
}
///
/// Logs the write.
///
/// The log message.
public void LogWrite(string logMessage)
{
logPath = HttpContext.Current.Server.MapPath("~");
logFormat = DateTime.Now.ToLongDateString().ToString() + " - " +
DateTime.Now.ToLongTimeString().ToString() + " ==> ";
try
{
using (StreamWriter writer = File.AppendText(logPath +
"\\" + "LogFile.txt"))
{
// Writes a string followed by a line terminator asynchronously to the stream.
//writer.WriteLineAsync(logFormat + logMessage );
writer.WriteLine(logFormat + logMessage);
}
}
catch (Exception ex)
{
//Do not do anything
}
}
}
}