I am writing a windows application using C#.net (4.5) I am asked to create a Debug Log for my software. How can I create it ?? Should I put debug log code after each line ??
-
4Perhaps you should ask some of those questions to the ones asking for a debug log? What do they intend to use it for? What kind of questions would such a log answer? To whom? In which situations? – Lasse V. Karlsen Mar 13 '14 at 11:25
-
2Simple trick I always do in web applications: Send a mail with the error to yourself, containing the stacktrace and the exception. When an error has been catched. – Max Mar 13 '14 at 11:27
5 Answers
How can I create it ?
Just pointing you in a right direction. You would want to look at logging frameworks, such as log4net or nlog (see comparison log4net vs nlog and here is some other frameworks).
Personally, I use log4net. I like it because the concepts are similar across different other languages - Java, C++. Once you know log4net, you can easily use log4j or log4xx.
Should I put debug log code after each line ?
No you shouldn't. You could, but that would usually generate too much debug info. Use it wisely to output useful and helpful information, so that when your program runs you can read the log and understand when things going in a wrong direction.
You should read about Aspect-Oriented Programming. You can inject this kind of behaviour through libraries such as Policy Injection Application Block, Castle, Spring.NET etc.

- 1,006
- 9
- 27
log4net is one option. You can get it from NuGet.
Then in your code you write statements like
LogManager.GetLogger("UserLog").Debug("User logged in:"+user);
You may use different levels such as Debug, Info, Error, Fatal and configure the system to log to different type of outputs such as plain file, db, etc.

- 2,116
- 2
- 19
- 29
Use Enterprise Library, many useful features like :
Logging Application Block.
Developers can use this application block to include logging functionality for a wide range of logging targets in their applications. This release adds asynchronous logging capabilities.

- 7,998
- 6
- 50
- 63
A very simple approach sufficient for many (single-threaded) situations:
Implement the following methods as static methods of a base-class Util
:
class Util
{
public static bool quiet; // flag to shut off o() Console output
public static StreamWriter fOut; // the output file for o()
public static int debugLevel = 2;
public static void o(string s)
{
if (!quiet)
{
Console.WriteLine(s);
}
if (fOut != null)
{
fOut.WriteLine(s);
}
}
public static void o2(string s)
{
if (debugLevel >= 2)
{
o(s);
}
}
}
You can now inherit this base class to whatever class you want to debug and intersperse calls to o()
. Controlled by the debugLevel
and the quiet
variable, you now get logging information either on the Console
or in a file.

- 10,544
- 2
- 31
- 54