tags:

views:

1712

answers:

2

I'm using log4net to log write log message to a rolling log file.

Now I would also redirect all trace messages from System.Diagnostics.Trace to that log file. How can I configure that? I tried to find anything about that in the log4net documentation, but without success. Is it possible at all?

The reason I want to do that is because I am interested in the Trace messages of a 3rd party library.

<log4net>
    <appender name="R1" type="log4net.Appender.RollingFileAppender">
      <file value="C:\Logs\MyService.log" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <maxSizeRollBackups value="10" />
      <datePattern value="yyyyMMdd" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
</log4net>
+8  A: 

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());

Rune Grimstad
+16  A: 

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

public class Log4netTraceListener : System.Diagnostics.TraceListener
{
    private static log4net.ILog logger = log4net.LogManager.GetLogger("System.Diagnostics.Redirection");

    public Log4netTraceListener(log4net.ILog logger)
    {
        Log4netTraceListener.logger = logger;
    }

    public override void Write(string message)
    {
        logger.Debug(message);
    }
    public override void WriteLine(string message)
    {
        logger.Debug(message);
    }
}
0xA3