Logging Exceptions/Errors in log file
using System.IO;
public string GetTempPath()
{
string path = System.Environment.GetEnvironmentVariable("TEMP");
if (!path.EndsWith("\\")) path += "\\";
return path;
}
public void LogMessageToFile(string msg)
{
System.IO.StreamWriter sw = System.IO.File.AppendText(
GetTempPath() + "My Log File.txt");
try
{
string logLine = System.String.Format(
"{0:G}: {1}.", System.DateTime.Now, msg);
sw.WriteLine(logLine);
}
finally
{
sw.Close();
}
}
With this simple method, all you need to do is to pass in a string like this:
LogMessageToFile("Hello, World");
The current date and time are automatically inserted to the log file along with your message.
0 Comments:
Post a Comment
<< Home