Skip to content

Conversation

AsakerMohd
Copy link
Contributor

Description:

Added new code to allow customers to manually instrument their PHP Lambda Handlers using Bref. This is based on Lambda Handler Instrumentation in .NET and other languages. I added a README on how to use but the idea here is that the customer will write their own handler function then call AWSLambdaWrapper::getInstance()->WrapFunctinon($originalHandler). The WrapFunction` uses a Tracer to create the lambda root span as a server span and add FAAS specific attributes to it regarding the handler function itself.

This is a full example:

<?php
// index.php

require __DIR__ . '/vendor/autoload.php';

use Bref\Context\Context;
use OpenTelemetry\Contrib\Aws\Lambda\AwsLambdaWrapper;

// Get AwsLambdaWrapper Instance which already constructs a Tracer to be used for creating spans
$wrapper = AwsLambdaWrapper::getInstance();

// Use the default tracer created by the wrapper to manually create and instrument other spans.
$tracer = $wrapper->getTracer();

// Alternatively, you can create your own tracer and then call $wrapper->setTracer($customTracer)

// Your PHP Handler Function and logic.
$originalHandlerFunction = function (array $event, Context $context) use ($tracer): array {
     // .... handler code using $tracer to manually instrument spans.
    return [
        'statusCode' => 404,
        'headers'    => ['Content-Type' => 'text/plain'],
        'body'       => 'Not Found',
    ];
};

// The WrapHandler Function is where you pass the original function and it gets instrumented
return $wrapper->WrapHandler($originalHandlerFunction);

Testing:

Wrote a minimal lambda function handler that using Bref and Serverless.

This is the example function:

<?php
// index.php

require __DIR__ . '/vendor/autoload.php';

use Bref\Context\Context;
use GuzzleHttp\Client;
use OpenTelemetry\API\Trace\SpanKind;
use OpenTelemetry\Contrib\Aws\Lambda\AwsLambdaWrapper;

$wrapper = AwsLambdaWrapper::getInstance();
$tracer = $wrapper->getTracer();

$handlerFunction = function (array $event, Context $context) use ($tracer): array {
    // Determine the request path
    $path = $event['rawPath'] ?? ($event['path'] ?? '/');

    error_log("this is event: " . print_r($event));

    // ──────────────────────────────────────────────────
    // Route: /outgoing-http-call
    // ──────────────────────────────────────────────────
    if ($path === '/outgoing-http-call') {
        $httpSpan  = $tracer->spanBuilder('http.call.aws.amazon.com')->setSpanKind(SpanKind::KIND_CLIENT)->startSpan();
        $httpScope = $httpSpan->activate();

        $client   = new Client();
        $response = $client->request('GET', 'https://aws.amazon.com');
        $body     = substr($response->getBody()->getContents(), 0, 200);

        $httpSpan->end();
        $httpScope->detach();

        return [
            'statusCode' => 200,
            'headers'    => ['Content-Type' => 'text/plain'],
            'body'       => $body,
        ];
    }

    return [
        'statusCode' => 404,
        'headers'    => ['Content-Type' => 'text/plain'],
        'body'       => 'Not Found',
    ];
};

return $wrapper->WrapHandler($handlerFunction);

After deploying to my AWS Account and triggering the function (with AWS X-Ray Tracing Enabled), below is a sample trace. From that trace, we can verify that:

  1. Propagation works as expected (extracting parent context and adding it to the new lambda span)
  2. Any child span created using the same tracer has the context propagated as well
  3. The Lambda Server span contains all the FAAS attributes as expected.
{
    "Id": "1-687df0da-7614120e07b2a22116526f84",
    "Duration": 0.282,
    "Segments": [
        {
            "Id": "4747e4579cbab420",
            "Document": {
                "id": "4747e4579cbab420",
                "name": "php-lambda-api-dev-api",
                "start_time": 1753084122.817,
                "trace_id": "1-687df0da-7614120e07b2a22116526f84",
                "end_time": 1753084123.035,
                "http": {
                    "response": {
                        "status": 200
                    }
                },
                "aws": {
                    "lambda.name": "php-lambda-api-dev-api",
                    "span.kind": "LOCAL_ROOT",
                    "xray.origin": "AWS::Lambda",
                    "request_id": "c9b9e9c1-ae8b-47d8-9764-0f81aee4514f"
                },
                "annotations": {
                    "aws:span.name": "php-lambda-api-dev-api/LambdaService",
                    "aws:aws.local.environment": "lambda:default",
                    "aws:aws.local.service": "php-lambda-api-dev-api",
                    "aws:span.kind": "SERVER",
                    "aws:aws.local.operation": "php-lambda-api-dev-api/LambdaService"
                },
                "metadata": {
                    "http.status_code": 200,
                    "cloud.provider": "aws",
                    "faas.invocation_id": "c9b9e9c1-ae8b-47d8-9764-0f81aee4514f",
                    "telemetry.extended": "true",
                    "service.name": "php-lambda-api-dev-api",
                    "faas.name": "php-lambda-api-dev-api",
                    "cloud.resource_id": "arn:aws:lambda:us-west-2:858348110546:function:php-lambda-api-dev-api",
                    "PlatformType": "AWS::Lambda",
                    "http.response.status_code": 200,
                    "faas.trigger": "http",
                    "cloud.platform": "aws_lambda"
                },
                "origin": "AWS::Lambda"
            }
        },
        {
            "Id": "11d503d22180b4f8",
            "Document": {
                "id": "11d503d22180b4f8",
                "name": "php-lambda-api-dev-api",
                "start_time": 1753084122.8238037,
                "trace_id": "1-687df0da-7614120e07b2a22116526f84",
                "end_time": 1753084122.988384,
                "parent_id": "8c97bf7c6f570d6f",
                "fault": false,
                "error": false,
                "throttle": false,
                "aws": {
                    "xray.error": false,
                    "xray.fault": false,
                    "span.kind": "SERVER",
                    "xray.throttle": false,
                    "xray": {
                        "auto_instrumentation": false,
                        "sdk_version": "1.6.0",
                        "sdk": "opentelemetry for php"
                    }
                },
                "annotations": {
                    "aws.local.service": "php-lambda-api-dev-api",
                    "span.name": "php-lambda-api-dev-api",
                    "aws.local.operation": "php-lambda-api-dev-api",
                    "span.kind": "SERVER",
                    "aws.local.environment": "lambda:default"
                },
                "metadata": {
                    "process.command_args": [
                        "/opt/bref/bootstrap.php"
                    ],
                    "process.runtime.version": "8.2.29",
                    "os.type": "linux",
                    "process.pid": 21,
                    "telemetry.sdk.name": "opentelemetry",
                    "os.version": "#1 SMP Fri Jun 20 19:15:06 UTC 2025",
                    "process.owner": "sbx_user1051",
                    "telemetry.sdk.language": "php",
                    "process.runtime.name": "cli",
                    "service.instance.id": "cfcdc0bc-d7c9-4ebb-88ab-8f1be7d61b4e",
                    "os.description": "5.10.238-254.954.amzn2.x86_64",
                    "faas.coldstart": true,
                    "host.arch": "x86_64",
                    "cloud.resource_id": "arn:aws:lambda:us-west-2:858348110546:function:php-lambda-api-dev-api",
                    "os.name": "Linux",
                    "host.name": "169.254.48.207",
                    "process.command": "/opt/bref/bootstrap.php",
                    "telemetry.sdk.version": "1.6.0",
                    "telemetry.extended": "true",
                    "service.name": "php-lambda-api-dev-api",
                    "cloud.region": "us-west-2",
                    "faas.name": "php-lambda-api-dev-api",
                    "cloud.provider": "aws",
                    "faas.invocation_id": "c9b9e9c1-ae8b-47d8-9764-0f81aee4514f",
                    "cloud.account.id": "858348110546",
                    "process.executable.path": "/opt/bin/php",
                    "faas.version": "$LATEST",
                    "PlatformType": "AWS::Lambda",
                    "faas.trigger": "http"
                },
                "subsegments": [
                    {
                        "id": "d155fe40607c1f85",
                        "name": "http.call.aws.amazon.com",
                        "start_time": 1753084122.8241358,
                        "end_time": 1753084122.938472,
                        "fault": false,
                        "error": false,
                        "throttle": false,
                        "aws": {
                            "xray.error": false,
                            "xray.fault": false,
                            "span.kind": "CLIENT",
                            "xray.throttle": false,
                            "xray": {
                                "auto_instrumentation": false,
                                "sdk_version": "1.6.0",
                                "sdk": "opentelemetry for php"
                            }
                        },
                        "annotations": {
                            "aws.local.service": "UnknownService",
                            "span.name": "http.call.aws.amazon.com",
                            "aws.local.operation": "UnmappedOperation",
                            "span.kind": "CLIENT",
                            "aws.remote.service": "UnknownRemoteService",
                            "aws.remote.operation": "UnknownRemoteOperation",
                            "aws.local.environment": "generic:default"
                        },
                        "metadata": {
                            "cloud.provider": "aws",
                            "telemetry.extended": "true",
                            "PlatformType": "Generic"
                        },
                        "namespace": "remote"
                    }
                ]
            }
        },
        {
            "Id": "7a4d4c4173a51116",
            "Document": {
                "id": "7a4d4c4173a51116",
                "name": "php-lambda-api-dev-api",
                "start_time": 1753084122.8216996,
                "trace_id": "1-687df0da-7614120e07b2a22116526f84",
                "end_time": 1753084123.0988395,
                "parent_id": "4747e4579cbab420",
                "aws": {
                    "account_id": "858348110546",
                    "lambda.name": "php-lambda-api-dev-api",
                    "xray.origin": "AWS::Lambda::Function",
                    "function_arn": "arn:aws:lambda:us-west-2:858348110546:function:php-lambda-api-dev-api",
                    "cloudwatch_logs": [
                        {
                            "log_group": "/aws/lambda/php-lambda-api-dev-api"
                        }
                    ],
                    "resource_names": [
                        "php-lambda-api-dev-api"
                    ]
                },
                "annotations": {
                    "aws:span.name": "php-lambda-api-dev-api/LambdaExecutionEnvironment",
                    "aws:span.kind": "SERVER"
                },
                "metadata": {
                    "cloud.provider": "aws",
                    "service.name": "php-lambda-api-dev-api",
                    "faas.name": "php-lambda-api-dev-api",
                    "cloud.resource_id": "arn:aws:lambda:us-west-2:858348110546:function:php-lambda-api-dev-api",
                    "cloud.platform": "aws_lambda"
                },
                "origin": "AWS::Lambda::Function",
                "subsegments": [
                    {
                        "id": "8c97bf7c6f570d6f",
                        "name": "Invocation",
                        "start_time": 1753084122.8217785,
                        "end_time": 1753084123.0346522,
                        "aws": {
                            "lambda.name": "Invocation",
                            "xray.origin": "AWS::Lambda::Function",
                            "function_arn": "arn:aws:lambda:us-west-2:858348110546:function:php-lambda-api-dev-api"
                        },
                        "annotations": {
                            "span.name": "Invocation/LambdaExecutionEnvironment",
                            "span.kind": "INTERNAL"
                        },
                        "metadata": {
                            "cloud.provider": "aws",
                            "service.name": "Invocation",
                            "faas.name": "Invocation",
                            "cloud.resource_id": "arn:aws:lambda:us-west-2:858348110546:function:php-lambda-api-dev-api",
                            "cloud.platform": "aws_lambda"
                        }
                    },
                    {
                        "id": "ca92aa97fa56201e",
                        "name": "Overhead",
                        "start_time": 1753084123.034683,
                        "end_time": 1753084123.0727952,
                        "aws": {
                            "lambda.name": "Overhead",
                            "xray.origin": "AWS::Lambda::Function",
                            "function_arn": "arn:aws:lambda:us-west-2:858348110546:function:php-lambda-api-dev-api"
                        },
                        "annotations": {
                            "span.name": "Overhead/LambdaExecutionEnvironment",
                            "span.kind": "INTERNAL"
                        },
                        "metadata": {
                            "cloud.provider": "aws",
                            "service.name": "Overhead",
                            "faas.name": "Overhead",
                            "cloud.resource_id": "arn:aws:lambda:us-west-2:858348110546:function:php-lambda-api-dev-api",
                            "cloud.platform": "aws_lambda"
                        }
                    }
                ]
            }
        },
        {
            "Id": "3d6d98351b7b61e9",
            "Document": {
                "id": "3d6d98351b7b61e9",
                "name": "http.call.aws.amazon.com",
                "start_time": 1753084122.8241358,
                "trace_id": "1-687df0da-7614120e07b2a22116526f84",
                "end_time": 1753084122.938472,
                "parent_id": "d155fe40607c1f85",
                "inferred": true,
                "annotations": {
                    "aws.local.service": "UnknownRemoteService",
                    "aws.local.operation": "UnknownRemoteOperation"
                }
            }
        }
    ]
}

@AsakerMohd AsakerMohd requested a review from a team as a code owner July 21, 2025 17:58
Copy link

codecov bot commented Jul 21, 2025

Codecov Report

❌ Patch coverage is 97.53086% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.26%. Comparing base (40eea2b) to head (59455f2).
⚠️ Report is 13 commits behind head on main.

Files with missing lines Patch % Lines
src/Aws/src/Lambda/AwsLambdaWrapper.php 97.53% 2 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff              @@
##               main     #408      +/-   ##
============================================
+ Coverage     83.07%   83.26%   +0.18%     
- Complexity     1530     1548      +18     
============================================
  Files            97       98       +1     
  Lines          6115     6196      +81     
============================================
+ Hits           5080     5159      +79     
- Misses         1035     1037       +2     
Flag Coverage Δ
Aws 93.41% <97.53%> (+0.82%) ⬆️
Context/Swoole 0.00% <ø> (ø)
Exporter/Instana 49.42% <ø> (ø)
Instrumentation/AwsSdk 81.13% <ø> (ø)
Instrumentation/CakePHP 20.40% <ø> (ø)
Instrumentation/CodeIgniter 73.55% <ø> (ø)
Instrumentation/Curl 90.42% <ø> (ø)
Instrumentation/Doctrine 92.92% <ø> (ø)
Instrumentation/ExtAmqp 88.48% <ø> (ø)
Instrumentation/ExtRdKafka 86.11% <ø> (ø)
Instrumentation/Guzzle 75.58% <ø> (ø)
Instrumentation/HttpAsyncClient 78.04% <ø> (ø)
Instrumentation/IO 70.68% <ø> (ø)
Instrumentation/MongoDB 74.28% <ø> (ø)
Instrumentation/MySqli 95.81% <ø> (ø)
Instrumentation/OpenAIPHP 87.21% <ø> (ø)
Instrumentation/PDO 94.21% <ø> (ø)
Instrumentation/Psr14 76.47% <ø> (ø)
Instrumentation/Psr15 89.15% <ø> (ø)
Instrumentation/Psr16 97.50% <ø> (ø)
Instrumentation/Psr18 77.46% <ø> (ø)
Instrumentation/Psr3 67.01% <ø> (ø)
Instrumentation/Psr6 97.61% <ø> (ø)
Instrumentation/ReactPHP 99.45% <ø> (ø)
Instrumentation/Slim 86.11% <ø> (ø)
Instrumentation/Symfony 84.88% <ø> (ø)
Logs/Monolog 100.00% <ø> (ø)
Propagation/Instana 98.11% <ø> (ø)
Propagation/ServerTiming 100.00% <ø> (ø)
Propagation/TraceResponse 100.00% <ø> (ø)
ResourceDetectors/Azure 91.66% <ø> (ø)
ResourceDetectors/Container 93.02% <ø> (ø)
ResourceDetectors/DigitalOcean 100.00% <ø> (ø)
Sampler/RuleBased 33.51% <ø> (ø)
Shims/OpenTracing 92.45% <ø> (ø)
Utils/Test 87.53% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/Aws/src/Lambda/AwsLambdaWrapper.php 97.53% <97.53%> (ø)

Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 40eea2b...59455f2. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@brettmc
Copy link
Contributor

brettmc commented Jul 22, 2025

Some tests and static analysis would be nice. Also need to add it to .github/workflows and .gitsplit.yaml

@AsakerMohd
Copy link
Contributor Author

Some tests and static analysis would be nice. Also need to add it to .github/workflows and .gitsplit.yaml

Let me add those and get back to you.

@AsakerMohd
Copy link
Contributor Author

Added unit tests for this new class. Didn't need to update the github/workflows and .gitsplit since the new AwsLambdaWrapper class is within the aws contrib pkg.

@brettmc brettmc merged commit da45e60 into open-telemetry:main Aug 25, 2025
141 of 153 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants