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.
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.
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.
I require to do logging into it....
Do you mean you wish to add logging to the application or that you want people to log in
?
To log thing to a file Log4Net exists to make it easy for you. If you don't want to rely on third party stuff then you could just do something like
Trace.Listeners.Clear();
if (options.Verbose)
{
var ctl = new ConsoleTraceListener(false) { TraceOutputOptions = TraceOptions.DateTime };
Trace.Listeners.Add(ctl);
}
if (options.Log)
{
var logFileFs = new FileStream("my.log", FileMode.Append);
var twtl = new TextWriterTraceListener(logFileFs)
{ TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime };
Trace.Listeners.Add(twtl);
}
Trace.AutoFlush = true;
Trace.WriteLine(DateTime.Now.ToString(CultureInfo.InvariantCulture) + " My App Started");
This enables you to add different outputs such as a log file and verbose printing to your ouput so that you could log to a file and also print it in console if the user has choose to use verbose output.
The line
Trace.WriteLine(DateTime.Now.ToString(CultureInfo.InvariantCulture) + " My App Started");
should be made into a function that takes your message and perhaps a log level so you have a uniform look to all your written log messages.
If you don't need that much functionality you could just write to the file stream directly.
there are many ways to log. You can use your own logging
else try Log4net it is simple configuration changes you are done.
Good article http://www.codeproject.com/Articles/140911/log4net-Tutorial
Just an additional info for you reg ELMAH(Another way of error logging) Using ELMAH in a console application
If you can use a third part product, go for log4net. It is a great logging framework for .NET.