【问题标题】:Does the Azure WebJobs SDK support pushing TextWriter logs into App Insights?Azure WebJobs SDK 是否支持将 TextWriter 日志推送到 App Insights?
【发布时间】:2016-12-15 00:00:26
【问题描述】:

使用 Azure WebJobs SDK,将日志记录添加到函数的过程相对简单:将 TextWriter 参数添加到触发函数,然后写入。而已。

然后,SDK 会将这些日志与其执行实例关联并显示在 WebJobs 仪表板中,该仪表板为您的 Web 作业的操作提供了一个相对丰富但无摩擦的视图。

虽然将此数据复制到用户可访问的 Azure 存储 Blob 容器中,但需要更多自定义代码才能定期将这些日志推送到 App Insights,这是不可取的。

寻找想法或解决方案,了解如何将通过注入的 TextWriter 推送的所有日志推送到 AppInsights(或 OMS,就此而言),完成 webjobs 执行/触发实例元数据,从而实现统一的消费体验各种日志分析。

基于在 WebJobs SDK 中跟踪的this Feature,我假设现在这是不可能的?很久以前,我试图注入我自己的 TextWriter 实例,但我不得不分叉 WebJobs SDK 并使用我的定制程序集,这改变了很多架构。

【问题讨论】:

    标签: azure azure-webjobs azure-webjobssdk


    【解决方案1】:

    您可以编写一个自定义TraceWriter 将日志发送到 AppInsights:

    using System.Collections.Generic;
    using System.Diagnostics;
    using Microsoft.ApplicationInsights;
    using Microsoft.Azure.WebJobs.Host;
    
    public class AppInsightsTraceWriter : TraceWriter
    {
        private readonly TelemetryClient _telemetryClient;
    
        public AppInsightsTraceWriter(TraceLevel level, TelemetryClient telemetryClient)
            : base(level)
        {
            _telemetryClient = telemetryClient;
        }
    
        public override void Trace(TraceEvent traceEvent)
        {
            var eventTelemetry = new EventTelemetry() {Name = "WebjobTraceEvent"};
            eventTelemetry.Properties.Add(traceEvent.Level.ToString(), traceEvent.ToString());
            _telemetryClient.TrackEvent(eventTelemetry);
        }
    }
    

    在本例中,我注入了TelemetryClient 类,因为您的应用程序中应该只有一个TelemetryClient 类的实例。

    所以现在您只需配置 Jobhost 即可使用您的自定义编写器:

    // Initialize the webjob configuration.
    var config = new JobHostConfiguration();
    
    // Only one instance of the telemetry client is needed
    var telemetryClient = new TelemetryClient() {InstrumentationKey = "MyInstrumentationKey"};
    
    // Add the app insights tracer for webjob logs/traces.
    config.Tracing.Tracers.Add(new AppInsightsTraceWriter(TraceLevel.Info, telemetryClient));
    
    // Detect when the webjob shut down
    var cancellationToken = new WebJobsShutdownWatcher().Token;
    cancellationToken.Register(() =>
    {
        // Before shut down, flush the app insights client.
        telemetryClient.Flush();
    });
    
    new JobHost(config).RunAndBlock();
    

    如果你有这样的功能:

    public static void ProcessQueueMessage([QueueTrigger("myqueue")] string logMessage, TextWriter log)
    {
        log.WriteLine(logMessage);
    }
    

    每次使用 log.WriteLine 时,都会向 App Insights 发送一个事件。

    注意:如果此示例也将来自 JobHost 的日志发送到 AppInsights。

    【讨论】:

    • 所以每次我现有的网络作业代码调用log.WriteLine(),都会发送到 AppInsights?或者仅当代码执行Trace.Write()?
    • 当你说 log.WriteLine() 时,log 是 TextWriter 的一个实例(作为你函数的参数)?
    • 是的。我会试一试。我一定错过了 JobHostConfig 上的跟踪可扩展性。
    【解决方案2】:

    这是超级旧的(不知道为什么 SO 决定在这么长时间后将它放在边栏中),但对于其他偶然发现这一点的人来说,应用洞察力现在是监控网络作业执行的推荐方法。

    在此处查看文档,了解如何将应用洞察与网络作业联系起来。

    此链接将引导您配置新 webjobs 项目的日志记录部分。检查前面的部分以确保您已具备所有先决条件。 https://docs.microsoft.com/en-us/azure/app-service/webjobs-sdk-get-started#add-application-insights-logging

    static async Task Main()
    {
        var builder = new HostBuilder();
        builder.UseEnvironment(EnvironmentName.Development);
        builder.ConfigureWebJobs(b =>
                {
                    b.AddAzureStorageCoreServices();
                    b.AddAzureStorage();
                });
        builder.ConfigureLogging((context, b) =>
                {
                    b.AddConsole();
    
                    // If the key exists in settings, use it to enable Application Insights.
                    string instrumentationKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
                    if (!string.IsNullOrEmpty(instrumentationKey))
                    {
                        b.AddApplicationInsightsWebJobs(o => o.InstrumentationKey = instrumentationKey);
                    }
                });
        var host = builder.Build();
        using (host)
        {
            await host.RunAsync();
        }
    }
    

    【讨论】:

    【解决方案3】:

    我将分享在 Azure Web Job 中使用 Application Insights 的详细步骤,请参考。

    1. 在 Azure 门户中创建新的 Azure Application Insights
    2. 在 Visual Studio 中创建 Azure Web Job 项目并安装 Microsoft.ApplicationInsights
    3. 设置检测密钥并发送 遥测

      public static void ProcessQueueMessage([QueueTrigger("queuename")] string message, TextWriter log)
      {
      
          TelemetryClient tc = new TelemetryClient();
      
          tc.InstrumentationKey = "key copied from Azure portal";
          tc.TrackTrace(message);
      
          tc.Flush();
      
          //log.WriteLine(message);
      }
      

    本文档解释了how to monitor usage and performance in Windows Desktop apps,您可以参考它以了解如何在非 Web 应用程序中使用 Azure Application Insights。此外,ApplicationInsights.Helpers.WebJobs 也有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      • 1970-01-01
      • 2018-05-06
      • 2018-08-16
      • 2016-08-30
      • 1970-01-01
      相关资源
      最近更新 更多