Tuesday, July 1, 2008

Write exceptions into error log(C#.net)

Try this console application code to write exceptions in to a log file.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
class errorlogs
{

String filepath = "C:/Documents and Settings/error/log.txt"; //path of errorlog file

static void Main(string[] args)
{
errorlogs er = new errorlogs();
object i = new IOException();
er.writelog(i); //passing the ioexception
}

public void writelog(object a){

try{
StreamWriter logWriter;
if(File.Exists(filepath)){
logWriter = File.AppendText(filepath);
}
else{
logWriter = File.CreateText(filepath);

}
logWriter.WriteLine();
logWriter.WriteLine("------"+ DateTime.Now +"--------");
logWriter.WriteLine();
logWriter.WriteLine(a);
logWriter.WriteLine();
logWriter.WriteLine("--------------------------------");
logWriter.Close();

}
catch(Exception e){
Console.Out.WriteLine("Error in writing errorlog:" +e.Message);
}
}

}
}

No comments: