Hi
I implemented the below function to create a log file that captures all errors that might occurred while my code is being executed. I call it in each catch block.
Example:
catch (IndexOutOfRangeException ex)
{
MessageBox.Show("File seems to be empty, skipping this file);
string exception = "File seems to be empty, skipping this file");
SkippedFiles += 1;
logFile(exception, file, SkippedFiles);
continue;
}
public void logFile(string ExceptionName, string fileName, int SkippedFiles)
{
StreamWriter log;
if (!File.Exists("logFile.txt"))
{
log = new StreamWriter("logFile.txt");
}
else
{
log = File.AppendText("logFile.txt");
}
//Write to the file:
log.WriteLine("Data Time: " + DateTime.Now);
log.WriteLine("File Name: " + fileName);
log.WriteLine("Number of Skipped Files: " + SkippedFiles);
log.WriteLine("Exception Name: " + ExceptionName);
log.WriteLine("End of the report");
log.WriteLine("\n===========================================================");
//close the stream:
log.Close();
}
Since I have multiple catch blocks, Is this the right way to call the log function?
Another thing. this will create the log file in the Bin\debug Dirctory. How to create it in any other directory or create it inside a folder which needs to be created (if errors occurred)
Abhishek JainPosted Aug 28, 2013, 9:09 AM
This can make your application slow as IO(input/output) operations are little slow then the in-memory operations. So you should try something which is asynchronous. Suppose that an exception comes, system fill open that file, but if that file is blocked by some other thread in the write mode then till that time your code will wait in the exception block for getting write permissions to that file. This can make your application very slow in deployment environment, if you are using threading or multiple application logs into same file.
For this either create a Service, which can accept your calls(one way calls), fire and forget technique, or they are other utilities which are present to achieve the same like Log4Net.
And as far as the location of your file is concerned, keep it anywhere and just provide the full path of the log file.