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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/515381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 06:24:13  来源:igfitidea点击:

How to log Trace messages with log4net?

c#.netlog4net

提问by Dirk Vollmar

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.Traceto 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?

现在我还将所有跟踪消息重定向System.Diagnostics.Trace到该日志文件。我该如何配置?我试图在 log4net 文档中找到任何关于它的信息,但没有成功。有可能吗?

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

我想这样做的原因是因为我对 3rd 方库的 Trace 消息感兴趣。

<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>

采纳答案by Dirk Vollmar

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

根据 Rune 的建议,我实现了一个输出到 log4net 的基本 TraceListener:

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

回答by Rune Grimstad

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

回答by Neil Dodson

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 仍然会产生上面评论中描述的问题。

回答by Billy Jake O'Connor

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