Skip to content

Azure-Samples/functions-quickstart-java-azd-otel

description This end-to-end Java sample demonstrates distributed tracing with OpenTelemetry across multiple Azure Functions in a Flex Consumption plan app with Service Bus integration and virtual network security.
page_type sample
products
azure-functions
azure
urlFragment functions-quickstart-java-azd-otel
languages
java
bicep
azdeveloper

Azure Functions Java Service Bus Trigger with OpenTelemetry Distributed Tracing using Azure Developer CLI

This template repository contains a Service Bus trigger reference sample for functions written in Java and deployed to Azure using the Azure Developer CLI (azd). The sample demonstrates distributed tracing using OpenTelemetry across multiple Azure Functions and includes managed identity and virtual network integration for secure deployment by default. This sample demonstrates these key features:

  • Distributed tracing with OpenTelemetry. The sample shows how to trace requests across multiple Azure Functions using OpenTelemetry integration, providing end-to-end visibility into function execution flows.
  • Virtual network integration. The Service Bus that this Flex Consumption app reads events from is secured behind a private endpoint. The function app can read events from it because it is configured with VNet integration. All connections to Service Bus and to the storage account associated with the Flex Consumption app also use managed identity connections instead of connection strings.

This project is designed to run on your local computer. You can also use GitHub Codespaces if available.

This sample demonstrates distributed tracing across multiple Azure Functions with OpenTelemetry integration. The app includes three functions that work together: an HTTP-triggered function that calls a second HTTP function, which then sends a message to Service Bus that triggers a third function. This creates a complete end-to-end tracing scenario that you can observe in Application Insights.

Important

This sample creates several resources. Make sure to delete the resource group after testing to minimize charges!

Prerequisites

Initialize the local project

You can initialize a project from this azd template in one of these ways:

  • Use this azd init command from an empty local (root) folder:

    azd init --template functions-quickstart-java-azd-otel

    Supply an environment name, such as flexquickstart when prompted. In azd, the environment is used to maintain a unique deployment context for your app.

  • Clone the GitHub template repository locally using the git clone command:

    git clone https://github.com/Azure-Samples/functions-quickstart-java-azd-otel.git
    cd functions-quickstart-java-azd-otel

    You can also clone the repository from your own fork in GitHub.

Prepare your local environment

  1. Create a file named local.settings.json in the root folder that contains this JSON data:

    {
        "IsEncrypted": false,
        "Values": {
            "AzureWebJobsStorage": "UseDevelopmentStorage=true",
            "FUNCTIONS_WORKER_RUNTIME": "java",
            "ServiceBusConnection__fullyQualifiedNamespace": "",
            "ServiceBusQueueName": "testqueue",
            "JAVA_APPLICATIONINSIGHTS_ENABLE_TELEMETRY": "true"
        }
    }

    [!NOTE] The ServiceBusConnection__fullyQualifiedNamespace will be empty for local development. You'll need an actual Service Bus connection for full testing, which will be provided after deployment to Azure.

Run your app from the terminal

  1. From the root folder, run these commands to build and start the Functions host locally:

    mvn clean package
    mvn azure-functions:run

    [!NOTE] The Service Bus trigger function will start but won't process messages until connected to an actual Service Bus queue. However, you can test the HTTP functions locally.

  2. The function will start and display the available functions. You should see output similar to:

    Functions:
        first_http_function: [GET,POST] http://localhost:7071/api/first_http_function
        second_http_function: [GET,POST] http://localhost:7071/api/second_http_function
        servicebus_queue_trigger: serviceBusTrigger
    
  3. You can test the HTTP functions locally by calling the endpoint, though the Service Bus functionality requires deployment to Azure for full testing.

  4. When you're done, press Ctrl+C in the terminal window to stop the func host process.

Run your app using Visual Studio Code

  1. Open the project root folder in Visual Studio Code.
  2. Press Run/Debug (F5) to run in the debugger.
  3. The Azure Functions extension will automatically detect your function and start the local runtime.
  4. The function will start and be ready to receive Service Bus messages (though local testing requires an actual Service Bus connection).

Source Code

The function app contains three functions that demonstrate distributed tracing across a complete request flow:

1. First HTTP Function

@FunctionName("first_http_function")
public HttpResponseMessage run(
        @HttpTrigger(
            name = "req", 
            methods = {HttpMethod.GET, HttpMethod.POST}, 
            authLevel = AuthorizationLevel.ANONYMOUS) 
        HttpRequestMessage<String> request,
        final ExecutionContext context) {
    
    context.getLogger().info("first_http_function function processed a request.");

    // Build base URI from the incoming request
    URI requestUri = request.getUri();
    String incomingUrl = requestUri.toString();
    String baseUrl = incomingUrl.split("/api/")[0] + "/api";
    String targetUri = baseUrl + "/second_http_function";

    // Get trace context from ExecutionContext and propagate it
    TraceContext traceContext = context.getTraceContext();
    // ... propagate traceparent and tracestate headers

    var client = HttpClient.newBuilder().build();
    var httpReq = HttpRequest.newBuilder(URI.create(targetUri)).GET().build();
    var resp = client.send(httpReq, HttpResponse.BodyHandlers.ofString());

    return request.createResponseBuilder(HttpStatus.OK)
            .body("Called second_http_function, status: " + resp.statusCode() + ", content: " + resp.body())
            .build();
}

2. Second HTTP Function

@FunctionName("second_http_function")
public HttpResponseMessage run(
        @HttpTrigger(
            name = "req",
            methods = {HttpMethod.GET, HttpMethod.POST},
            authLevel = AuthorizationLevel.ANONYMOUS)
            HttpRequestMessage<String> request,
        @ServiceBusQueueOutput(
            name = "message",
            queueName = "%ServiceBusQueueName%",
            connection = "ServiceBusConnection")
            OutputBinding<String[]> serviceBusMessages,
        final ExecutionContext context) {
    
    context.getLogger().info("second_http_function function processed a request.");

    // Send message to Service Bus queue
    serviceBusMessages.setValue(new String[] { "Hello" });

    return request.createResponseBuilder(HttpStatus.OK)
            .body("Hello from second_http_function!")
            .build();
}

3. Service Bus Queue Trigger

@FunctionName("servicebus_queue_trigger")
public void run(
    @ServiceBusQueueTrigger(
        name = "message",
        queueName = "%ServiceBusQueueName%",
        connection = "ServiceBusConnection")
        String message,
    final ExecutionContext context
) {
    context.getLogger().info("Message Body: " + message);
}

Distributed Tracing Flow

This architecture creates a complete distributed tracing scenario:

  1. First HTTP function receives an HTTP request and calls the second HTTP function
  2. Second HTTP function responds and sends a message to Service Bus
  3. Service Bus trigger processes the message

Key aspects of the implementation:

  • OpenTelemetry integration: The host.json file configures OpenTelemetry mode for distributed tracing
  • Function chaining: The first function calls the second using Java HttpClient with trace context propagation
  • Service Bus integration: The second function outputs to Service Bus using output bindings, which triggers the third function
  • Managed identity: All Service Bus connections use managed identity instead of connection strings
  • Java 17: Uses Java 17 for modern language features and performance

The function configuration in host.json enables OpenTelemetry:

{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  },
  "telemetryMode": "OpenTelemetry"
}

Key configuration aspects:

  • OpenTelemetry: "telemetryMode": "OpenTelemetry" enables distributed tracing across function calls
  • Azure Monitor Integration: Azure Monitor exporter sends telemetry to Application Insights
  • Trace Context Propagation: The first function manually propagates trace context headers to maintain distributed traces

Deploy to Azure

Run this command to provision the function app, with any required Azure resources, and deploy your code:

azd up

You're prompted to supply these required deployment parameters:

Parameter Description
Environment name An environment that's used to maintain a unique deployment context for your app. You won't be prompted if you created the local project using azd init.
Azure subscription Subscription in which your resources are created.
Azure location Azure region in which to create the resource group that contains the new Azure resources. Only regions that currently support the Flex Consumption plan are shown.

After deployment completes successfully, azd provides you with the URL endpoints and resource information for your new function app.

Test the solution

  1. Once deployment is complete, you can test the distributed tracing functionality by calling the first_http_function:

  2. Call the first HTTP function: Use the function URL provided after deployment to trigger the complete distributed tracing flow:

    https://your-function-app.azurewebsites.net/api/first_http_function
    
  3. View distributed tracing in Application Insights:

    • Navigate to your Application Insights resource in the Azure Portal
    • Open the "Application map" to see the distributed trace across all three functions
    • Check the "Transaction search" to find your request and see the complete trace timeline
    • The trace will show: HTTP request → first_http_function → second_http_function → Service Bus message → servicebus_queue_trigger

The Application Insights telemetry will show the complete distributed trace:

  • The HTTP request to first_http_function
  • The internal HTTP call to second_http_function
  • The Service Bus message being sent
  • The servicebus_queue_trigger processing the message through the VNet-secured Service Bus

This demonstrates end-to-end distributed tracing across multiple Azure Functions with OpenTelemetry integration.

Redeploy your code

You can run the azd up command as many times as you need to both provision your Azure resources and deploy code updates to your function app.

Note

Deployed code files are always overwritten by the latest deployment package.

Clean up resources

When you're done working with your function app and related resources, you can use this command to delete the function app and its related resources from Azure and avoid incurring any further costs:

azd down

Resources

For more information on Azure Functions, Service Bus, OpenTelemetry, and VNet integration, see the following resources:

About

No description, website, or topics provided.

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors