首页 > 解决方案 > Serilog 与 Application Insights 的 Azure 功能集成,日志在搜索中可见但未出现在故障事件时间线中

问题描述

我正在尝试将 Serilog 与 Application Insights sink 一起用于记录目的。我可以在 Azure 门户 (Application Insights) 的搜索栏中看到日志,但如果我们在失败或性能选项卡中查看事件的时间线,则看不到相同的日志。谢谢

下面是用于在 FunctionStartup 中注册 Logger 的代码,然后将其注入到 Function 中进行日志记录:

var logger = new LoggerConfiguration()
                               .Enrich.FromLogContext()
                               .Enrich.WithProperty("ApplicationName", "testApp")
                               .Enrich.WithProperty("Environment", "Dev")                               
                               .WriteTo.ApplicationInsights(GetTelemetryClient("Instrumentationkey"), TelemetryConverter.Traces)
                               .CreateLogger();
builder.Services.AddSingleton<ILogger>(logger);

Telementory Client 正在从辅助方法中获取:

public static TelemetryClient GetTelemetryClient(string key)
        {
            var teleConfig = new TelemetryConfiguration { InstrumentationKey = key };

            var teleClient = new TelemetryClient(teleConfig);

            return teleClient;
        }

主机.json

{
    "version": "2.0",
    "logging": {
        "applicationInsights": {
            "samplingExcludedTypes": "Request",
            "samplingSettings": {
                "isEnabled": true
            }
        }
    }
}

标签: .net-coreazure-functionsazure-application-insightsserilog

解决方案


我明白了,请允许我在这里总结一下我的测试结果。

首先,故障刀片不是为提供用于跟踪细节(异常发生之前发生的事情)的时间线而设计的,而是为了显示所有异常、错误发生的频率、受影响的用户数量等,它是更有可能站在高处看到整个节目。

为了实现您的目标,我认为您可以在刀片中使用此 kql 查询Logs或在事务刀片中观看它。

union traces, requests,exceptions
| where operation_Id == "178845c426975d4eb96ba5f7b5f376e1"

在此处输入图像描述 基本上,我们可能会在执行链中添加许多日志,例如在控制器中,记录输入参数,然后记录数据合并或格式化的结果,将异常信息记录在 中catch,这是我的测试代码。我无法像您一样在故障刀片中看到任何其他信息,但在事务刀片中,我可以看到时间线。

public class HelloController : Controller
    {
        public string greet(string name)
        {
            Log.Verbose("come to greet function");
            Log.Debug("serilog_debug_info");
            Log.Information("greet name input " + name);
            int count = int.Parse(name);
            Log.Warning("enter greet name is : {0}", count);
            return "hello " + name;
        }
    }

在此处输入图像描述

我们可以很容易地发现,整个链共享相同的operationId,并且通过所有这些日志,我们可以查明错误的行代码。顺便说一句,如果我用 try/catch 包围代码,则故障刀片中不会捕获异常。

====================================

使用Serilog 集成应用洞察,我们需要将 serilog 发送到应用洞察,我们会Traces在交易搜索中看到很多,所以最好将其MinimumLevel设置为信息和更高。下面的截图是我的日志详情,我们也可以通过 operationId 使用 kql 查询来查看整个链条。

在此处输入图像描述


推荐阅读