【问题标题】:How to intercept an Azure WebJob failure / exception如何拦截 Azure WebJob 失败/异常
【发布时间】:2017-05-23 04:08:22
【问题描述】:

当前在 Azure 中,当 WebJob 引发异常时,异常会被JobHost(不知何故)捕获和处理,然后将异常记录到仪表板,该仪表板可通过托管 Web 作业的 Web 应用的刀片提供.有什么方法可以拦截错误处理或覆盖它,以便我可以插入我的 Application Insights 实例?

【问题讨论】:

标签: c# azure azure-webjobs azure-application-insights


【解决方案1】:

您可以使用Azure WebJobs SDK Extensions:有一个ErrorTrigger,以便您可以使用拦截未处理的异常:

public class UnhandledErrorTrigger : IDisposable
{
    private readonly TelemetryClient _telemetryClient;

    public UnhandledErrorTrigger(TelemetryClient telemetryClient)
    {
        _telemetryClient = telemetryClient;
    }              

    public void UnHandledException([ErrorTrigger("0:01:00", 1)] TraceFilter filter, TextWriter log)
    {
        foreach (var traceEvent in filter.Events)
        {
            _telemetryClient.TrackException(traceEvent.Exception);
        }

        // log the last detailed errors to the Dashboard
        log.WriteLine(filter.GetDetailedMessage(1));
    }

    public void Dispose()
    {
        _telemetryClient.Flush();
    }
}

要注册错误扩展,请在您的启动代码中调用config.UseCore()

private static void Main()
{
    var config = new JobHostConfiguration();
    config.UseCore();

    ...
    new JobHost(config).RunAndBlock();
}

因此,如果您使用的是 IoC 容器,则可以轻松注入 TelemetryClient。要为网络作业配置作业激活器,您可以查看这篇文章:

【讨论】:

    【解决方案2】:

    查看一些 azure 文档 here。您可以将处理程序附加到 AppDomain 处理未知异常(取自上面的链接):

    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; 
    
    // ... 
    
    private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) 
    { 
        ExceptionTelemetry excTelemetry = new ExceptionTelemetry((Exception)e.ExceptionObject); 
        excTelemetry.SeverityLevel = SeverityLevel.Critical; 
        excTelemetry.HandledAt = ExceptionHandledAt.Unhandled; 
    
        telemetryClient.TrackException(excTelemetry); 
    
        telemetryClient.Flush(); 
    } 
    

    【讨论】:

    • 其实我在 Raygun 的文档中发现了类似的东西。这种方法的问题是,我不能保证我在作业期间建立的任何指标或额外属性都会被记录下来,除非我为每个可能的 throw 语句建立了一些非常混乱的异常处理。如果我要进入我们的那种逻辑,我还不如直接检测作业方法
    • hmmm...我目前正在考虑使用一些字典来存储键/值对,这些键/值对可以存储在全局属性中,该属性可用于存储要传递给 AI 的信息。跨度>
    • @AlexMarshall 你是网络作业中的 DI 容器吗?
    • 是的,我愿意。我们目前正在使用 Ninject
    • @AlexMarshall,我添加了一个关于 ErrorTrigger 的答案
    猜你喜欢
    • 2016-03-14
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多