简体   繁体   English

如何使用log4net记录跟踪消息?

[英]How to log Trace messages with log4net?

I'm using log4net to log write log message to a rolling log file. 我正在使用log4net将写入日志消息记录到滚动日志文件中。

Now I would also redirect all trace messages from System.Diagnostics.Trace to that log file. 现在,我还将所有跟踪消息从System.Diagnostics.Trace重定向到该日志文件。 How can I configure that? 我该如何配置? I tried to find anything about that in the log4net documentation, but without success. 我试图在log4net文档中找到有关此内容的任何内容,但均未成功。 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>

According to Rune's suggestion I implemented a basic TraceListener which output to log4net: 根据Rune的建议,我实现了一个基本的TraceListener,输出到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. 我不知道log4net是否支持此功能,但是您可以实现自己的跟踪侦听器来执行此操作。

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. TraceListener没有太多需要实现的方法,您所要做的就是将值转发到log4net,因此这应该很容易做到。

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()); 要添加自定义跟踪侦听器,您可以修改app.config / web.config或使用Trace.Listeners.Add(new Log4NetTraceListener());将其添加到代码中Trace.Listeners.Add(new Log4NetTraceListener());

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/ 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: 为了粗略地处理从LogLog类发出的内部log4net跟踪的问题(在上一个答案的注释中进行了描述),我通过检查堆栈框架(此实现已对此进行检查)来​​检查此类是否为跟踪的源,并且忽略那些跟踪消息:

    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. 使用TraceAppender仍会产生上述注释中描述的问题。

Thanks, 谢谢,

I went with Dirk's answer slimmed down a bit. 我同意了Dirk的答案。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM