Why Log file needed ?
: Log files are needed for developer to understand flow of code/applications and most important to track/trace the errors in application. If we consider the case of execptions/errors in code sometimes we are unable to trace them at run time. So writing log file really help to overcome for tracking error locations.
Here is sample code written in Visual C-sharp :
See the Class below:
public class YourLogger
{
public static void WriteLogToFile(string yourlogMsg)
{
public static string logFile = @"Path/LogFileName.txt";
try
{
FileStream myFileStream = null;
//creates file if not exist
if (File.Exists(LogFileName) == false)
{
FileStream fs = new FileStream(LogFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
fs.Close();
}
else
{
myFileStream = new FileStream(LogFileName, FileMode.Append, FileAccess.Write);
}
StreamWriter myStreamWriter = new StreamWriter(myFileStream);
myStreamWriter.WriteLine(DateTime.Now.ToString() + "\t" + yourlogMsg);
myStreamWriter.Flush();
myStreamWriter.Close();
myFileStream.Close();
}
catch
{
//Do your exception related operations
}
}
}
Now call WriteLogToFile(string yourlogMsg) method your application specifically
in Catch block to logg the exception details .
Code to call :
YourLogger.WriteLogToFile(exceptionObject.Message);
Hope this might be helpful for new developer.
Good Info buddy!!
ReplyDelete-Lakshmi