Akka.NET记录器未将日志发送到Application Insights

ekqde3dh  于 2022-11-06  发布在  .NET
关注(0)|答案(1)|浏览(134)

我已经在Akka.NET中将ApplicationInsights设置为日志提供程序,并设置了Akka.Monitoring来记录各种自定义指标(例如对接收到的消息进行计数和对处理持续时间进行计时)。
但是我使用Akka.NET的logger生成的日志没有被发送到ApplicationInsights:

var logger = Logging.GetLogger(Context);
logger.Info($"Please send me to Azure!");

我希望在Application Insights的Traces部分中看到它沿着我的其他.NET核心日志项。但是,这些日志确实出现在我的运行时输出中,我假设它是stdout。
Application Insights使用Akka.Monitoring.ApplicationInsights进行配置,如下所示:

ActorMonitoringExtension.RegisterMonitor(system, new ActorAppInsightsMonitor(instrumentationKey));

解决方案:

由于Peter的回答,我不得不为此实现一个自定义日志记录器:

public class ApplicationInsightsLogger
        : ReceiveActor
{
    private readonly TelemetryClient _telemetry = new TelemetryClient();

    private readonly IDictionary<LogLevel, SeverityLevel> _logLevelMap = new Dictionary<LogLevel, SeverityLevel>()
    {
        { LogLevel.DebugLevel, SeverityLevel.Verbose },
        { LogLevel.InfoLevel, SeverityLevel.Information },
        { LogLevel.WarningLevel, SeverityLevel.Warning },
        { LogLevel.ErrorLevel, SeverityLevel.Error },
    };

    public ApplicationInsightsLogger()
    {
        Receive<LogEvent>(message => this.Log(message.LogLevel(), message));
        Receive<InitializeLogger>(_ => Sender.Tell(new LoggerInitialized()));
    }

    private void Log(LogLevel level, LogEvent item)
    {
        if (!_logLevelMap.ContainsKey(level))
        {
            throw new InvalidOperationException($"{level} log level isn't handled.");
        }

        SeverityLevel severity = _logLevelMap[level];

        _telemetry.TrackTrace(new TraceTelemetry()
        {
            Message = item.Message.ToString(),
            SeverityLevel = severity,
            Timestamp = item.Timestamp,
            Properties = { { "Source", item.LogSource } }
        });

        if (item is Error)
        {
            _telemetry.TrackException(new ExceptionTelemetry()
            {
                Message = item.Message.ToString(),
                SeverityLevel = severity,
                Timestamp = item.Timestamp,
                Properties = { { "Source", item.LogSource } },
                Exception = (item as Error).Cause
            });
        }
    }
}
o7jaxewo

o7jaxewo1#

快速浏览一下就会发现,对App Insights的调用只有TrackMetrics调用。要发送类似logger.Info($"Please send me to Azure!");的日志消息,应该是对TrackTrace的调用。因此,我认为该库只对跟踪指标有用,而不是消息。这一点进一步得到了软件包描述的证实:
监视是Akka.NET的ActorSystem扩展,它公开了一个可插拔层,用于报告从参与者返回到监视系统的性能指标,例如...
无论如何,documentation并不表示存在可用的Application Insights记录器。

相关问题