Error logging in C#
I am making my switch from coding in C++ to C#. I need to replace my C++ error logging/reporting macro system with something similar in C#.
In my C++ source I can write
LOGERR("Some error"); or LOGERR("Error with inputs %s and %d", stringvar, intvar);
The macro & supporting library code then passes the (possibly varargs) formatted message into a database along with the source file, source line, user name, and time. The same data is also stuffed into a data structure for later reporting to the user.
Does anybody have C# code snippets or pointers to examples that do this basic error reporting/logging?
Edit: At the time I asked this question I was really new to .NET and was unaware of System.Diagnostics.Trace. System.Diagnostics.Trace was what I needed at that time. Since then I have used log4net on projects where the logging requirements were larger and more complex. Just edit that 500 line XML configuration file and log4net will do everything you will ever need :)
Solution 1:
Lots of log4net advocates here so I'm sure this will be ignored, but I'll add my own preference:
System.Diagnostics.Trace
This includes listeners that listen for your Trace()
methods, and then write to a log file/output window/event log, ones in the framework that are included are DefaultTraceListener
, TextWriterTraceListener
and the EventLogTraceListener
. It allows you to specify levels (Warning,Error,Info) and categories.
Trace class on MSDN
Writing to the Event Log in a Web Application
UdpTraceListener - write log4net compatible XML messages to a log viewer such as log2console
Solution 2:
I would highly recommend looking at log4Net. This post covers the majority of what you need to get started.
Solution 3:
Another good logging library is NLog, which can log to a lot of different places, such as files, databases, event logger etc.
Solution 4:
I use The Object Guy's Logging Framework--as do most people who try it. This guy has some interesting comments about it.
Solution 5:
Enterprise Library is a solid alternative to log4net and it offers a bunch of other capabilities as well (caching, exception handling, validation, etc...). I use it on just about every project I build.
Highly recommended.