Azure / Azure-Functions

1.11k stars 198 forks source link

How to add metadata to traces in Azure functions #1384

Open nishantsny opened 5 years ago

nishantsny commented 5 years ago

I have an Azure function(.NET core 2.0) that runs on each PR in an ADO repo. I would like to add the PR-ID as metadata to each trace logged by the Azure function. (I am viewing the logs using the traces table in the Azure application insights instance)

The Azure function logs traces via:

public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, ILogger log, ExecutionContext context)
{
  logger.LogInformation("Trace Message");
}

How can I add additional metadata to each trace?

Expecho commented 5 years ago

How about using an AsyncLocal in the Azure Function like outlined here?

public class CustomTelemetryInitializer : ITelemetryInitializer
{
    public static AsyncLocal<string> MyValue = new AsyncLocal<string>();

    public void Initialize(ITelemetry telemetry)
    {
        if (telemetry is ISupportProperties propertyItem)
        {
            propertyItem.Properties["myProp"] = MyValue.Value;
        }
    }
}

Question to the team: I've read you can safely use AsyncLocal in an Azure Function, can you confirm.