问题
We have a internally-developed logging system, and we wanted to gain the benefits of log4net such as being able to use multiple appenders simultaneously. We decided to move the legacy logging system into a custom log4net appender. That worked great when the legacy system was configured correctly, but the legacy logger actually writes to a WCF client (making it slow for verbose logging, the reason we wanted to engage other log4net appenders), and recently the WCF configuration was not quite what it should have been. When this happened the application seemed to run ok, but obviously the custom appender for the legacy system was not working. The other appenders worked fine, but there was no output from the custom legacy appender and no error messages indicating that there was a problem.
What is the proper way to handle "recursive" logging, that is logging from inside a custom log4net appender? I tried a naive solution: grabbing log4net from its static object and logging inside the appender:
public class MyCustomAppender : AppenderSkeleton
{
protected override void Append(log4net.Core.LoggingEvent loggingEvent)
{
try
{
// something which throws here...
}
catch (Exception ex)
{
log4net.LogManager.GetLogger(this.GetType()).Error(this.GetType().ToString() + ": error during append", ex);
}
}
}
This was an abject failure, "System.Threading.LockRecursionException: Recursive read lock acquisitions not allowed in this mode." Fair enough; it was the naive solution.
I also tried:
this.ErrorHandler.Error(this.GetType().ToString() + ": error during append", ex);
in the exception handler, as it seemed possible it might be the right thing. Nothing obvious happened.
Is there a way to log errors through log4net inside an appender? Or do I have to do something like hard-code writing to the windows event log directly? Obviously there is great danger of infinite recursive descent, but I would think there would be some way of letting the operator know that one of the appenders failed to run.
JR
回答1:
Of course as soon as I posted the question, I remembered something. log4net has a debugging switch inside the appSettings. I used this code:
this.ErrorHandler.Error(this.GetType().ToString() + ": error during append", ex);
inside the catch block, then set the magic setting on:
<appSettings>
<!--this is wonderful magic-->
<add key="log4net.Internal.Debug" value="true" />
</appSettings>
Now the ConsoleAppender (the other appender I was using) put out the custom appender exception message.
JR
回答2:
Make sure you have this line at top: using System.Threading;
来源:https://stackoverflow.com/questions/33261138/logging-error-handling-inside-a-custom-log4net-appender