Log4net 不登录到 Application Insights

Log4net doesn't log to Application Insights

我正在为我的 MVC 应用程序使用 log4net。 log4net.config 文件独立于 web.config。我将 ApplicationInsights.Log4NetAppender 添加到我的 UI 项目并将 aiAppender 从 web.config 移动到 log4net.config。应用程序能够以某种方式将数据记录到 Logs.txt,但它不会记录到 ApplicationInsights。

请帮我解决这个问题。 这是我的 log4net.config:

<log4net>
  <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender" >
    <file value="App_Data/Logs/Logs.txt" />
    <encoding value="utf-8" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="10" />
    <maximumFileSize value="10000KB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5level %date [%-5.5thread] %-40.40logger - %message%newline" />
    </layout>
  </appender>
  <appender name="aiAppender" type="Microsoft.ApplicationInsights.Log4NetAppender.ApplicationInsightsAppender, Microsoft.ApplicationInsights.Log4NetAppender">
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5level %date [%-5.5thread] %-40.40logger - %message%newline" />
    </layout>
  </appender>
  <root>
    <level value="DEBUG" />
    <appender-ref ref="RollingFileAppender" />
    <appender-ref ref="aiAppender" />
  </root>
</log4net>

applicationinsights 的 InstrucmentationKey 正在从应用程序设置中读取。

TelemetryConfiguration.Active.InstrumentationKey = WebConfigurationManager.AppSettings["InstrumentationKey"];

在 AdaptiveSamplingTelemetryProcessor 中,我正在使用自适应采样。

<Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
  <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
  <ExcludedTypes>Event</ExcludedTypes>
</Add>

我可以看到所有依赖项和请求都记录在 ApplicationInsights 上,但无法从 log4net 中找到任何数据。

如果是log4net的问题,最好开启log4net内部调试:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
    <add key="log4net.Internal.Debug" value="true"/>
</appSettings>
</configuration>

并将其写入文件:

<configuration>
...

<system.diagnostics>
    <trace autoflush="true">
        <listeners>
            <add 
                name="textWriterTraceListener" 
                type="System.Diagnostics.TextWriterTraceListener" 
                initializeData="C:\tmp\log4net.txt" />
        </listeners>
    </trace>
</system.diagnostics>

...
</configuration>

如果有任何异常,您会在日志文件中找到它。也可能是 AI 记录器使用了缓冲,或者应用程序见解正在缓冲并且在您的应用程序退出时未刷新。

more on Log4net Troubleshooting

flush application insights when your ASP.NET Core application exits