如何在应用程序见解中处理来自webjobs的异常?

时间:2019-04-23 14:54:20

标签: azure azure-webjobs azure-application-insights azure-webjobssdk

当从webjob抛出异常时,它退出而不记录到应用程序见解。观察到将日志刷新到应用程序见解需要花费几分钟,因此我们在这里遗漏了异常。该如何处理?

还有一种方法,可以将碰到异常的消息自动移动到中毒队列,而无需手动将该消息插入中毒队列?

我正在为2个NuGet软件包使用最新的稳定的3.x版本: Microsoft.Azure.WebJobs和Microsoft.Azure.WebJobs.Extensions

创建一个实现了IHost的主机,如下所示:

        var builder = new HostBuilder()
            .UseEnvironment("Development")
            .ConfigureWebJobs(b =>
            {
                ...
            })
            .ConfigureLogging((context, b) =>
            {
                string appInsightsKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
                if (!string.IsNullOrEmpty(appInsightsKey))
                {
                    b.AddApplicationInsights(o => o.InstrumentationKey = appInsightsKey);
                    appInsights.TrackEvent("Application Insights is starting!!");
                }
            })
            .ConfigureServices(services =>
            {
              ….
            })
            .UseConsoleLifetime();
        var host = builder.Build();
        using (host)
        {
            host.RunAsync().Wait();
        }

和Function.cs

   public static async void ProcessQueueMessageAsync([QueueTrigger("queue")] Message message, int dequeueCount, IBinder binder, ILogger logger)
    {
        switch (message.Name)
        {
            case blah:
                ...break;
            default:
                logger.LogError("Invalid Message object in the queue.", message);
                logger.LogWarning("Current dequeue count: " + dequeueCount);
                throw new InvalidOperationException("Simulated Failure");
        }
    }

我的问题是:

1)遇到默认情况时,webjob立即终止,并且即使在等待并再次启动web作业之后,记录器也不会陷入对应用程序的见解中。由于需要几分钟来反映应用洞察力,并且webjob停止,因此我丢失了错误日志。该如何处理?

2)从此处的示例Web作业中,https://github.com/Azure/azure-webjobs-sdk-samples/blob/master/BasicSamples/QueueOperations/Functions.cs他们正在使用JobHost host = new JobHost();并且如果“ FailAlways”功能失败,它将自动重试5次并将消息推送到中毒队列。但这在我的代码中没有发生。是因为主机不同?还是我必须添加更多配置?

2 个答案:

答案 0 :(得分:0)

检查了Application Insights SDK的源代码后,很明显,要在Application Insights中获取异常,必须将异常对象传递到LogError调用中。

log.Error(ex, "my error message") - will result in Application Insight Exception

log.Error("my error message") - will result in Application Insight Trace.
  

有没有一种方法可以自动将碰到异常的消息移至中毒队列,而无需手动将该消息插入中毒队列?

您可以在网络作业中设置config.Queues.MaxDequeueCount = 1;。将消息移到中毒队列之前尝试处理该消息的次数。

  

在代码中应该在哪里添加MaxDequeueCount配置?

您可以在program.cs的JobHostConfiguration中设置属性

答案 1 :(得分:0)

尝试更改函数以返回Task而不是void

public static async Task ProcessQueueMessageAsync([QueueTrigger("queue")] Message message, int dequeueCount, IBinder binder, ILogger logger)

这对我很有用,即使我正在记录错误并抛出异常,Application Insights要么显示成功调用,要么不显示调用。

相关问题