Tigraine

Daniel Hoelbling-Inzko talks about programming

Writing ELMAH Exceptions to Log4Net

Posted by Daniel Hölbling on November 22, 2009

Yesterday a friend asked me if I know how to make ELMAH write exceptions to a Log4Net appender.
My first idea was to write a custom ErrorLog that would do that, but that’s not really possible since ELMAH must be able to retrieve errors after the fact so they can be displayed in ELMAH’s web interface.

Well, turns out it’s even simpler and more obvious by simply subclassing an existing ErrorLog and hook into the Log method:

image

Assuming you use the XmlFileErrorLog (you can use this method with all of them) you simply subclass it and put your call to Log4Net before the base.Log call:

public class Log4NetErrorLog : XmlFileErrorLog
{
    public Log4NetErrorLog(IDictionary config) : base(config)
    {
    }

    public Log4NetErrorLog(string logPath) : base(logPath)     {     }

    readonly ILog log = LogManager.GetLogger("bla");     public override string Log(Error error)     {         //Write whatever you want to Log4Net         log.Fatal("Exception logged through ELMAH: " + error.Message, error.Exception);         return base.Log(error);     } }

Now the only thing you have to do is change the errorLog line in your ELMAH configuration (found in web.config) to reference your new ErrorLog subclass:

<elmah>  
    <errorLog type="MyAssembly.Log4NetErrorLog, MyAssembly" logPath="~/App_Data" />  
</elmah>

It will still log to XML, but also generate one entry per log to Log4Net. If you don’t want to save anything you can simply subclass the MemoryErrorLog class and set it’s size to 1.

Filed under net, programmierung
comments powered by Disqus

My Photography business

Projects

dynamic css for .NET

Archives

more