检索 Azure 函数触发器信息

Retrieve Azure function trigger info

有没有办法从执行上下文中检索 Azure 函数触发器信息(如服务总线主题名称)?我试图创建通用的 LogError 函数,它可以在不同的 azure 函数中使用,如下例所示:

[FunctionName("azureFunctionName")]
public static async Task RunNormal(
    [ServiceBusTrigger(topicName: "events-topic", subscriptionName: "events-processmanager-sub", 
        Connection = "processManagers_Listen_SERVICEBUS")]
    string eventMessage,
    CancellationToken cancellationToken, ILogger log)
{
    try
    {
        //... do some work here
    }
    catch (Exception e)
    {
        LogError(log, e)
        throw;
    }
}

private static void LogError(ILogger log, Exception e) 
{
    // **** somehow find topic and subscription from the context here ?? ****
    var topicName = ...
    var subscriptionName = ...

    log.LogCritical(e, "Failed to process message from {topic}/{subscription}", topicName, subscriptionName);
}

这是一种方法,可以让您获取属性并从属性中获取所有必需的信息:

static class TriggerDiscoverer
{
    /// <summary>
    /// Attempts to derive the required configuration information from the Azure Function and trigger attributes via reflection.
    /// </summary>
    public static TTriggerAttribute TryGet<TTriggerAttribute>() where TTriggerAttribute : Attribute
    {
        var frames = new StackTrace().GetFrames();
        foreach (var stackFrame in frames)
        {
            var method = stackFrame.GetMethod();
            var functionAttribute = method.GetCustomAttribute<FunctionNameAttribute>(false);
            if (functionAttribute != null)
            {
                foreach (var parameter in method.GetParameters())
                {
                    var triggerConfiguration = parameter.GetCustomAttribute<TTriggerAttribute>(false);
                    if (triggerConfiguration != null)
                    {
                        return triggerConfiguration;
                    }
                }

                return null;
            }
        }

        return null;
    }
}

对于服务总线触发的函数,它将按以下方式调用:

var attribute = TriggerDiscoverer.TryGet<ServiceBusTriggerAttribute>();

并访问所有信息:

attribute.QueueName
attribute.TopicName
attribute.SubscriptionName
attribute.Connection