How to log Trace messages with log4net?

According to Rune's suggestion I implemented a basic TraceListener which output to log4net:

public class Log4netTraceListener : System.Diagnostics.TraceListener
{
    private readonly log4net.ILog _log;

    public Log4netTraceListener()
    {
        _log = log4net.LogManager.GetLogger("System.Diagnostics.Redirection");
    }

    public Log4netTraceListener(log4net.ILog log)
    {
        _log = log;
    }

    public override void Write(string message)
    {
        if (_log != null)
        {
            _log.Debug(message);
        }
    }

    public override void WriteLine(string message)
    {
        if (_log != null)
        {
            _log.Debug(message);
        }
    }
}

I don't know if log4net supports this, but you could implement your own trace listener that did this.

The TraceListener doesn't have too many method that needs to be implemented and all you would do is to forward the values to log4net so this should be easy to do.

To add a custom trace listener you would either modify your app.config/web.config or you would add it in code using Trace.Listeners.Add(new Log4NetTraceListener());

Tags:

C#

.Net

Log4Net