user1746174 user1746174 - 25 days ago 17
C# Question

Logging from a console application

I have created a console application which transfers data from an excel sheet and transfers it to a database. I require to do logging into it.

How can i go about it? because i have absolutely no idea about how to go about it.

Answer

If you simply want to write text to a file as your log you can do something like the following:

string strLogText = "Some details you want to log.";

// Create a writer and open the file:
StreamWriter log;

if (!File.Exists("logfile.txt"))
{
  log = new StreamWriter("logfile.txt");
}
else
{
  log = File.AppendText("logfile.txt");
} 

// Write to the file:
log.WriteLine(DateTime.Now);
log.WriteLine(strLogText);
log.WriteLine(); 

// Close the stream:
log.Close();

Source of this code is from this article.
Here is some documentation of the StreamWriter Class.

Otherwise if you want something more you can do as others have suggested and check out Log4Net.

Comments