views:

12785

answers:

15
+21  Q: 

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 :)

+5  A: 

Even though I personally hate it, log4net seems to be the de facto standard for C# logging. Sample usage:

log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
log.Error(“Some error”);
log.ErrorFormat("Error with inputs {0} and {1}", stringvar, intvar);
Ben Hoffstein
what's wrong with log4Net?
Mitch Wheat
It gets the job done, but I hate the documentation and am resentful for having spent many hours tinkering with config files and basically flying blind until I could get relatively simple things working the way I wanted them to.
Ben Hoffstein
I've used log4net and appreciate it's a powerful tool (and NHibernate and others use it). But I'm curious why people don't like using the .NET 2.0 inbuilt tracing? With the different type of listeners and a few tools it seems a lot less messy than log4net, which is a java port.
Chris S
Can hear you about the documentation (somewhat). Which is why looking at the code of decent open source projects that utilize it is a huge time saver. After that, it's by far my favorite logging utility.
Ted
@Ted: a nice idea - Would you care to recommend a couple of projects to look at to learn about logging?
fostandy
+18  A: 

I would highly recommend looking at log4Net. This post covers the majority of what you need to get started.

Mitch Wheat
Would the downvoter please leave a comment. Thanks.
Mitch Wheat
+1  A: 

Log4Net is a rather comprehensive logging framework that will allow you to log to different levels (Debug, Error, Fatal) and output these log statements to may different places (rolling file, web service, windows errors)

I am able to easily log anywhere by creating an instance of the logger

private static readonly ILog _log = LogManager.GetLogger(typeof([Class Name]));

and then logging the error.

_log.Error("Error messsage", ex);
FryHard
+7  A: 

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.

spoon16
EL can even send out emails as part of the logging. Very handy when reporting prod errors.
StingyJack
+1  A: 

Ditto for log4net. I'm adding my two bits because for actual use, it makes sense to look at some open source implementations to see real world code samples with some handy additions. For log4net, I'd suggest off the top of my head looking at subtext. Particularly take a look at the application start and assemblyinfo bits.

Ted
+4  A: 

Another good logging library is NLog, which can log to a lot of different places, such as files, databases, event logger etc.

Mats Fredriksson
I haven't heard of that one.
Mitch Wheat
+21  A: 

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

Chris S
+1 Small addition, Trace is active if and only if you've compiled with the TRACE preprocessor symbol.
sixlettervariables
One thing to note with the TextWriterTraceListener is it doesn't do timestamps
Chris S
@Chris: You can override the `WriteLine()` method in the `TextWriterTraceListener` to achieve automatic time-stamping capability in the log file. See [this CodeProject article](http://www.codeproject.com/KB/dotnet/customnettracelisteners.aspx), section 6.
Robert Harvey
+1  A: 

Further to the couple of comments realting to the use of the System.Diagnostics methods for logging, I would also like to point out that the DebugView tool is very neat for checking debug output when needed - unless you require it, there is no need for the apps to produce a log file, you just launch DebugView as and when needed.

Chris Ballard
A: 

Log4Net, as others have said, is fairly common and similar to Log4j which will help you if you ever do any Java.

You also have the option of using the Logging Application Block http://www.codeproject.com/KB/architecture/GetStartedLoggingBlock.aspx

Mario
+1  A: 

You can use built in .NET logging. Look into TraceSource and TraceListeners, they can be configured in the .config file.

CSharpAtl
+8  A: 

I use The Object Guy's Logging Framework--as do most people who try it. This guy has some interesting comments about it.

+3  A: 

As I said in another thread, we've been using The Object Guy's Logging Framework in multiple production apps for several years. It's super easy to use and extend.

S. Mills
+1  A: 

The built in tracing in System.Diagnostics is fine in the .NET Framework and I use it on many applications. However, one of the primary reasons I still use log4net is that the built in .NET Framework tracing lacks many of the useful full featured appenders that log4net already supplies built in.

For instance there really isn't a good rolling file trace listener defined in the .NET Framework other than the one in a VB.NET dll which really is not all that full featured.

Depending on your development environment I would recommend using log4net unless 3rd party tools are not available, then I'd say use the System.Diagnostics tracing classes. If you really need a better appender/tracelistener you can always implement it yourself.

For instance many of our customers require that we do not use open source libraries when installed on their corporate machines, so in that case the .NET Framework tracing classes are a perfect fit.

Additionally - http://www.postsharp.org/ is an AOP library I'm looking into that may also assist in logging as demonstrated here on code project:http://www.codeproject.com/KB/dotnet/log4postsharp-intro.aspx.

Wil P
A: 

Have a look at http://www.matthiasgruber.com/joomla/index.php/downloads I have released a very flexible and lightweight logging framework for .NET 4.0 (written in C#) there. It is extremely easy to use and nearly everything can be configured manually.

Matthias
+1  A: 

Am I right in thinking Log4Net is a bit out of date at the moment?

I have tried NLog (http://nlog.codeplex.com/) which I think is great for simple plug-n-play capability, there is no mountains of pre-config you have to do.

Trouble I am having is finding something that is engineered to work with .NET 3.0 onwards, a lot of my projects will be moving to .NET 3.5/4.0 Framework and I am finding there isn't really much out there (admittedly I haven't taken a look at the inbuilt tracing in the framework).

Cheers,

K

Kermit
qstarin