如何通过依赖项注入正确设置Azure函数日志、实时指标和应用程序洞察 [英] How to properly set up Azure Functions logging, live metrics, and app insights with dependency injection

查看:29
本文介绍了如何通过依赖项注入正确设置Azure函数日志、实时指标和应用程序洞察的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大约一个月前,我注意到旧的Azure Functions门户界面中的一些监控功能停止工作。我在Azure Functions Host GitHub上写了更多关于这些问题的详细信息,但我的具体问题到目前为止还没有得到回答。

现在似乎Azure函数门户界面默认使用新的"管理体验",看起来更类似于Azure的睡觉,有了它,我们使用日志记录和跟踪的方式就更明显出了问题。

我的问题是:有没有人有关于如何设置Azure函数日志、实时度量和应用洞察力跟踪的代码示例,以便:

  1. 使用依赖项注入
  2. 使用新的"管理体验"界面

目前,为了查看特定的Azure函数正在做什么,我必须转到旧的Azure界面并研究日志流。这些函数确实起作用了,它们会在日志流中输出信息,但只是在旧的界面中,在监视方面似乎没有太多效果。使用旧接口:

  • 当您按下"Functions(Read Only)">[Function]>Monitor下的"Monitor"链接时获得的调用日志根本不显示任何调用,即使这些函数确实是根据日志调用的。
  • "实时应用指标"链接将导致默认的"不可用:您的应用脱机或使用较旧的SDK"以及一些动画演示图表。

这些在一个月前工作得很好。现在,就没那么多了。

使用新界面:

  • 监视>日志流不考虑详细程度,只显示"Connected!"一词。
  • 监控>日志流>再次在Live Metrics中打开只会生成默认值"不可用:您的应用脱机或使用较旧的SDK"。

使用函数>函数>[单击函数]转到新界面中的特定函数:

  • 开发人员>代码+测试>测试按钮>运行,日志窗口弹出,只显示"已连接!"不考虑冗长,也不考虑其他内容。
  • Monitor>调用,此处没有注册调用跟踪,即使该函数显然是根据旧接口日志流调用的。
  • 监视器>日志同样只显示"已连接!",而不考虑详细程度。

我不明白为什么一个月前它突然停止工作,为什么这么多东西在新界面上似乎不起作用。我们函数的NuGet包都是最新的。

在日志记录方面,记录器是依赖项注入的,因此我们可以在多个类中使用它,而不仅仅是在默认的Functions.cs类中使用:

using Microsoft.Extensions.Logging;

public class EventForwarder
{
    private readonly ILogger<EventForwarder> log;

我们通过使用扩展方法登录,没什么特别的:

using Microsoft.Extensions.Logging;

public static class LoggerExtensions
{
    public static void Info(this ILogger log, string msg) => log.LogInformation(msg);

应用程序洞察跟踪程序也是使用建议的解决方法here注入依赖项的,即我们的Startup.cs看起来很简单:

using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(EventForwarder.Startup))]
namespace EventForwarder
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            // https://github.com/Azure/azure-functions-host/issues/5353
            builder.Services.AddSingleton(sp =>
            {
                var key = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");
                return string.IsNullOrWhiteSpace(key) ? new TelemetryConfiguration() : new TelemetryConfiguration(key);
            });

我们正在执行跟踪http重试等操作,如下所示:

public class HttpRetryPolicyService
{
    private readonly ILogger<HttpRetryPolicyService> log;
    private readonly TelemetryClient insights;

    public HttpRetryPolicyService(ILogger<HttpRetryPolicyService> log,
        TelemetryConfiguration insightsConfig)
    {
        this.log = log;
        insights = new TelemetryClient(insightsConfig);
    }
...
private void LogRetry(DelegateResult<HttpResponseMessage> message, TimeSpan delay, int attempt, Context context)
{
    if (message.Exception != null)
    {
        log.Warn($"Exception details: {message.Exception}");
        insights.Track(message.Exception);

我们使用扩展方法进行跟踪,如下所示:

using Microsoft.ApplicationInsights;

namespace EventForwarder.Static
{
    public static class TelemetryExtensions
    {
        public static void Track(this TelemetryClient insights, string eventName)
        {
            insights.TrackEvent(eventName);
            insights.Flush();
        }

我错过了什么?

编辑#1:顺便说一下,很遗憾,将Application Insight作为服务依赖项添加到发布对话框中不能解决这些问题。

Edit#2:另外,我们的函数host.json文件都如下所示:

{
    "version": "2.0",
    "healthMonitor": {
        "enabled": true,
        "healthCheckInterval": "00:00:10",
        "healthCheckWindow": "00:02:00",
        "healthCheckThreshold": 6,
        "counterThreshold": 0.80
    },
    "logging": {
        "fileLoggingMode": "always",
        "applicationInsights": {
            "enableLiveMetrics": true,
            "samplingSettings": {
                "isEnabled": true
            }
        },
        "logLevel": {
            "EventForwarder": "Information"
        }
    }
}

推荐答案

这就是破坏您的应用程序的原因,删除它,一切都会正常工作:

// https://github.com/Azure/azure-functions-host/issues/5353
builder.Services.AddSingleton(sp =>
{
    var key = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");
    return string.IsNullOrWhiteSpace(key) ? new TelemetryConfiguration() : new TelemetryConfiguration(key);
});

我的猜测是,既然修补程序已经推出,解决方法实际上会破坏日志记录。

我创建了一个示例应用程序,其中日志记录和日志流可以很好地工作,也可以使用依赖项注入。我用Windows和Linux消费计划对其进行了测试。功能应用程序是使用Azure门户中的向导创建的,选择.NET Core 3.1。请注意,TrackEvent不会出现在函数的日志流中。它显示在Application Insight Live Metrics中。在显示";Connected&Quot;之后,还可能需要长达30秒的时间,直到显示实际日志。"实时指标"视图工作得更好,尤其是在您直接从应用程序洞察力中打开时。

通过应用上面提到的解决方法&,我能够重现您的问题。没有它,一切都很正常。

完整样本:https://github.com/LXBdev/Functions-V3-sample

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddScoped<MyService>();
    }
  "logging": {
    "applicationInsights": {
      "samplingExcludedTypes": "Request",
      "samplingSettings": {
        "isEnabled": true
      }
    },
    "logLevel": {
      "Functions_V3_sample": "Information"
    }
  }
public MyService(ILogger<MyService> logger, TelemetryClient telemetry)
{
    Logger = logger ?? throw new ArgumentNullException(nameof(logger));
    Telemetry = telemetry ?? throw new ArgumentNullException(nameof(telemetry));
}

public void Foo()
{
    Logger.LogInformation("Foo");
    Telemetry.TrackTrace("BarLog", Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Information);
    Telemetry.TrackEvent("BarEvent");
}

更新:我最初回答的host.json有问题,由于https://github.com/Azure/azure-functions-host/issues/4345,示例日志没有真正保存到AppInsight。我相应地更新了代码。

这篇关于如何通过依赖项注入正确设置Azure函数日志、实时指标和应用程序洞察的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆