tags:

views:

541

answers:

3

Log4net is a little too good at not throwing errors. I am trying to create some kind of handler that fires if log4net can not start or dies and can no longer log.

I am aware of the app settings key to turn on log4net's internal debugging (log4net.Internal.Debug). I don't need all the debugging information all the time though, just if there is an issue with log4net.

Does anyone have a way they have programmatically captured and handled errors in log4net?

+1  A: 

Well, log4net will make it very hard for you to do this, since it will (by design) suppress exceptions which are thrown during logging operations. That's because a production system shouldn't fail because of an error while formatting a log message.

It's worth trying with very simple pattern layouts, as sometimes it's the use of %P{XYZ} elements in pattern layouts which cause problems if the corresponding properties are not properly set. If everything works as expected with a simple pattern layout, you can add the things you need back in one at a time and see if you can pinpoint the problem that way.

Vinay Sajip
This does seem to be correct. During the few times that we have needed it, we have been turning on log4net.Internal.Debug.
Dustin Venegas
+1  A: 

Something that may work for you is to create a class that implements IErrorHandler for each appender, then configure each appender to use the custom error handling class. This should give you more control than enabling log4net.Internal.Debug.

I've just given this a try and it works (note that in my sample Logger is a log4net logger defined elsewhere - the aim behin this is capture errors from an SMTP appender and log them to a file):

using System;

using log4net.Core;

namespace Test
{
    public class SmtpErrorHandler : IErrorHandler
    {
     public void Error(string message)
     {
      Logger.Log.Error(message);
     }

     public void Error(string message, Exception ex)
     {
      Logger.Log.Error(message, ex);
     }

     public void Error(string message, Exception ex, ErrorCode errorCode)
     {
      Logger.Log.Error(String.Format("{0}{1}Error code: {2}", message, Environment.NewLine, errorCode), ex);
     }
    }
}

Where I configure my appender (of course you can do this in the config too):

emailAppender.ErrorHandler = new SmtpErrorHandler();
Cocowalla
A: 

We created our own custom class which performs Logger.Log.Error... and if a exception is thrown or something went wrong, we write the original error and also the exception into the Windows Event Log.

When analyzing the errors, the user has to send us not only the logfiles, but also the event log. We created a tool which automatically exports the event logs and compress them together with all available Log4net logfiles into a zip file.

Thomasek