简体   繁体   English

Azure WebJobs SDK 是否支持将 TextWriter 日志推送到 App Insights 中?

[英]Does the Azure WebJobs SDK support pushing TextWriter logs into App Insights?

With the Azure WebJobs SDK, the process of adding logging to your functions is relatively straightforward: Add a TextWriter param to your triggered function, and write to it.使用 Azure WebJobs SDK,向函数添加日志记录的过程相对简单:将 TextWriter 参数添加到触发函数,然后写入。 That's it.就是这样。

The SDK will will then associate and display these logs with their execution instances in the WebJobs Dashboard, which provides a relatively data-rich, yet frictionless view into the operationalization of your webjobs.然后,SDK 会将这些日志与其在 WebJobs 仪表板中的执行实例相关联并显示出来,该仪表板提供了一个数据相对丰富但无障碍的 Web 作业操作视图。

While this data is replicated into a user-accessible Azure Storage Blob Container, more custom code would be required to periodically push these logs to App Insights, which is undesirable.虽然此数据被复制到用户可访问的 Azure 存储 Blob 容器中,但需要更多自定义代码来定期将这些日志推送到 App Insights,这是不可取的。

Looking for ideas or solutions for how to push all logs pushed via the injected TextWriter to be pushed to AppInsights (or OMS, for that matter), complete with the webjobs execution/trigger instance metadata, thereby allowing a unified consumption experience for various log analytics.寻找关于如何将所有通过注入的 TextWriter 推送的日志推送到 AppInsights(或 OMS,就此而言)的想法或解决方案,以及 webjobs 执行/触发实例元数据,从而为各种日志分析提供统一的消费体验.

Based on this Feature being tracked in the WebJobs SDK, I'm assuming that for now this is not possible?基于 WebJobs SDK 中正在跟踪的此功能,我假设目前这是不可能的? A long while back I looked into trying to inject my own TextWriter instance, but I would've had to fork the WebJobs SDK and use my customized assembly that changed a lot of architecture.很久以前,我曾考虑尝试注入我自己的 TextWriter 实例,但我不得不分叉 WebJobs SDK 并使用我的自定义程序集,该程序集改变了很多架构。

You can write a custom TraceWriter that sends log to AppInsights:您可以编写一个自定义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);
    }
}

In this example, I inject the TelemetryClient class because you should only have one instance of the TelemetryClient class in your application.在此示例中,我注入TelemetryClient类,因为您的应用程序中应该只有TelemetryClient类的一个实例。

So now you just need to configure the Jobhost to use your custom writer :所以现在您只需要配置Jobhost以使用您的自定义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();

So if you have a function like that:所以如果你有这样的功能:

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

Every time you use log.WriteLine, an event will be sent to App Insights.每次使用 log.WriteLine 时,都会向 App Insights 发送一个事件。

Note : if this sample also logs from the JobHost are sent to AppInsights.注意:如果此示例也将来自 JobHost 的日志发送到 AppInsights。

This is super old (not sure why SO decided to put it in the sidebar for me after this long) but for anyone else that stumbles upon this, app insights is now the recommended way to monitor webjob executions.这是非常古老的(不知道为什么 SO 决定在这么长时间后为我把它放在侧边栏中)但是对于其他任何偶然发现的人来说,应用程序洞察现在是监视 webjob 执行的推荐方式。

Check out the documentation here which steps through the process of connecting app insights to webjobs.查看此处的文档,其中逐步介绍了将应用洞察连接到 webjobs 的过程。

This link walks you through configuring the logging portion of a new webjobs project.此链接将引导您配置新 webjobs 项目的日志记录部分。 Check through the earlier sections to make sure that you've got all the prerequisites.检查前面的部分以确保您已具备所有先决条件。 https://docs.microsoft.com/en-us/azure/app-service/webjobs-sdk-get-started#add-application-insights-logging 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();
    }
}

I will share the detailed steps to use Application Insights in Azure Web Job, please refer to it.我将分享在 Azure Web Job 中使用 Application Insights 的详细步骤,请参考。

  1. Create an new Azure Application Insights in Azure portal在 Azure 门户中创建新的 Azure Application Insights
  2. Create Azure Web Job project in Visual Studio and install Microsoft.ApplicationInsights在 Visual Studio 中创建 Azure Web 作业项目并安装 Microsoft.ApplicationInsights
  3. Set the instrumentation key and send telemetry设置仪表键并发送遥测

    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); }

This documentation explained how to monitor usage and performance in Windows Desktop apps , you could refer to it to know how to use Azure Application Insights in non-web application.本文档解释了如何在 Windows 桌面应用程序中监控使用情况和性能,您可以参考它了解如何在非 Web 应用程序中使用 Azure Application Insights。 Besides, ApplicationInsights.Helpers.WebJobs could be also helpful.此外, ApplicationInsights.Helpers.WebJobs也有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM