How to log Trace messages with log4net?

C#.NetLog4net

C# Problem Overview


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>

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Solution 3 - C#

As per the answers above, there's an implementation here (this link is flaky, but I did find the source code):

https://code.google.com/archive/p/cavity/

To crudely deal with the issue (described in the comments to a previous answer) of internal log4net trace issuing from the LogLog class, I checked for this class being the source of the trace by inspecting the stack frame (which this implementation did already) and ignoring those trace messages:

    public override void WriteLine(object o, string category)
    {
        // hack to prevent log4nets own diagnostic trace getting fed back
        var method = GetTracingStackFrame(new StackTrace()).GetMethod();
        var declaringType = method.DeclaringType;
        if (declaringType == typeof(LogLog))
        {
            return;
        }
        /* rest of method writes to log4net */
    }

Using a TraceAppender will still create the problems described in the comments above.

Solution 4 - C#

Thanks,

I went with Dirk's answer slimmed down a bit.

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

    public Log4netTraceListener()
        : this(log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType))
    {
       
    }

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

    public override void Write(string message) => _log?.Debug(message);

    public override void WriteLine(string message) => _log?.Debug(message);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDirk VollmarView Question on Stackoverflow
Solution 1 - C#Dirk VollmarView Answer on Stackoverflow
Solution 2 - C#Rune GrimstadView Answer on Stackoverflow
Solution 3 - C#Neil DodsonView Answer on Stackoverflow
Solution 4 - C#Billy Jake O'ConnorView Answer on Stackoverflow