Click to See Complete Forum and Search --> : Creating log files


ujjwalmeshram
February 28th, 2008, 08:18 AM
Hi I m new to c#. I have made a calculator application.

I have given it to client for testing.
Client got some errors and he called me. When I reched to him, he was unable to explain me about the error.


Now I want to modify the program to create a log file(text file) which will store all the events generated by the programm i.e. what inputs are given by user, whta were the values of variables etc..

Means whatever the program will do, I want all that information in log file. so that if any error occurs atclient side, I can trace the error by looking at log file

I think the above explaination is enough to understand my problem.

If u ve any idea or suggestions plz share with me

Thank u

DeepT
February 28th, 2008, 08:40 AM
I created a log file class for some CPP applications, I am sure it would work the same way under C#. I have no idea if there are any special log file API calls.

Basically create a static class that can be called anywhere, like Logger.WriteLog(), or Logger.SetLogLevel(), etc...

The WriteLog function should probably perpend some extra info on each log line such as the current date and time, and perhaps the calling class and method.

The other thing you need to worry about is making sure you do not do unnecessary string operations because they are very expensive and will add up when you gets 100s of log statements in your code.

For example: Logger.WriteLog(3, string.format("The User Name is : %s", userName));

The problem with that is that even if logging is turned off the string.format() is still called every time you pass by it in code. This is bad.

You would want something like:
if ( Logger.CurrentLogLevel >= 3) { Logger.WriteLog(3, ...)));

In CPP I made a macro for that kind of stuff so my code didn't look ugly, but I do not think there is a way to do that in C#.

Anyhow that should give you a starting point.

torrud
February 28th, 2008, 09:17 AM
Another way is to use the Trace namespace or tools like Log4net (http://logging.apache.org/log4net/). I think there is no need to write an own logger by yourself.

boudino
February 29th, 2008, 01:29 AM
Or you can use Logging Application Block from Microsoft Enterprise Library (http://msdn2.microsoft.com/cs-cz/library/aa480453(en-us).aspx). It is free and it works. We are using it on enterprise application.

mariocatch
March 6th, 2008, 10:15 PM
I personally have setup a Logging class that like an above poster said, contains a static WriteToLog(String) method.