Joost
Joost

Reputation: 394

Add custom telemetry properties inside Azure Function

I have an Azure Function (v2) where data is passed in as JSON via the HTTP body. I want to log some of this JSON data in Application Insights, using the standard Trace and Request events.

What I've tried so far:

Ideally I want to use the data which is parsed inside my Function, and use that data to initialize the telemetry data.

Upvotes: 5

Views: 3365

Answers (1)

Liudmila Molkova
Liudmila Molkova

Reputation: 351

  1. You can update request telemetry properties by adding tags on Activity.Current like Activity.Current?.AddTag("my-prop", ExtractPropFromRequest()); Without any additional changes, these tags will appear on requests. Unfortunately, you won't get them stamped on traces.

  2. You can also parse your request body once in the function and store it in AsyncLocal. Then access this AsyncLocal in the TelemetryInitializer

 public class AsyncLocalPropertyTelemetryInitializer : ITelemetryInitializer
 {
   public void Initialize(ITelemetry telemetry)
     {
       if (telemetry is ISupportProperties propTelemetry &&
           Function1.AdditionalContext.Value != null) // you may find a better way to make it work with DI
         {
           propTelemetry.Properties["my-prop"] = Function1.AdditionalContext.Value;
         }
      }
  }


public static class Function
{
    internal static readonly AsyncLocal<string> AdditionalContext = new AsyncLocal<string>();
    [FunctionName("Function1")]
    public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
    {
      AdditionalContext.Value = "something important"; // read the body here
      log.LogInformation("C# HTTP trigger function processed a request.") 
      AdditionalContext.Value = null;
      // ...
    }
  }
}

Upvotes: 6

Related Questions