Получить Azure информацию о срабатывании функции - PullRequest
1 голос
/ 07 февраля 2020

Есть ли способ получить Azure информацию о запуске функции (например, имя служебной шины topi c) из контекста выполнения? Я пытался создать функцию generi c 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);
}

1 Ответ

1 голос
/ 07 февраля 2020

Вот подход, который позволил бы вам добраться до атрибута и получить из него всю необходимую информацию:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...