log4net 写“?”当我使用 %type、%method 和 %line 模式时

log4net writes '?' when I use `%type, %method and %line` patterns

我正在尝试在我的 c# ASP.net Core 2.2 应用程序中使用 log4net,但是当我使用这些模式中的任何一个时,它们会给我带问号的输出。

我的log4net.config:

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file value="C:\Temp\app.log" />
    <layout type="log4net.Layout.PatternLayout">
     <conversionPattern value="%date | %level | [%thread] | %type %method %line - %message%n" />
    </layout>
  </appender>
  <root>
    <level value="ALL" />
    <appender-ref ref="RollingFile" />
  </root>
</log4net>

写入日志后文件如下所示:

2019-04-17 11:48:44,230 | INFO | [1] | ? ? ? - abc

知道为什么会发生这种情况以及如何解决这个问题吗? 我看到了一些使用这些模式的教程,并尝试从中复制,但结果是一样的……也许我的配置有问题?

来自 here 我知道我可以将文件名和行添加到我的消息中,但我想先尝试在配置文件中进行修复。

谢谢。

我将您的配置复制粘贴到我的项目中,它按预期工作。您 运行 您的项目是发布版还是调试版?您是否了解这些模式的局限性?

Note about caller location information. The following patterns %type %file %line %method %location %class %C %F %L %l %M all generate caller location information. Location information uses the System.Diagnostics.StackTrace class to generate a call stack. The caller's information is then extracted from this stack.

The System.Diagnostics.StackTrace class is not supported on the .NET Compact Framework 1.0 therefore caller location information is not available on that framework.

The System.Diagnostics.StackTrace class has this to say about Release builds:

StackTrace information will be most informative with Debug build configurations. By default, Debug builds include debug symbols, while Release builds do not. The debug symbols contain most of the file, method name, line number, and column information used in constructing StackFrame and StackTrace objects. StackTrace might not report as many method calls as expected, due to code transformations that occur during optimization.

This means that in a Release build the caller information may be incomplete or may not exist at all! Therefore caller location information cannot be relied upon in a Release build.

编辑

.net 核心/.net 标准 StackTrace 未完全支持:

https://github.com/apache/logging-log4net/blob/master/src/Core/LocationInfo.cs#L86

因此 classNamefileNamelineNumbermethodNamefullInfo 不可用。