-
Notifications
You must be signed in to change notification settings - Fork 76
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add logfire.instrument_aws_lambda
#657
Merged
Merged
Changes from 9 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
091a29c
Add `logfire.instrument_aws_lambda`
Kludex 259b8b7
Add logfire-api
Kludex 30060e6
Add test
Kludex 71e2f1d
add lmd function param
Kludex 8888d8e
fix docs
Kludex 6192d2d
fix test
Kludex 38cbfc9
Merge branch 'main' into aws-lambda-integration
Kludex bc37379
update test
Kludex 0b9e185
Add LambdaFunction type
Kludex e102454
Use lambda_handler
Kludex 2434e73
Merge branch 'main' into aws-lambda-integration
Kludex File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
# AWS Lambda | ||
|
||
The [`logfire.instrument_aws_lambda`][logfire.Logfire.instrument_aws_lambda] function can be used to | ||
instrument AWS Lambda functions to automatically send traces to **Logfire**. | ||
|
||
## Installation | ||
|
||
Install `logfire` with the `aws-lambda` extra: | ||
|
||
{{ install_logfire(extras=['aws-lambda']) }} | ||
|
||
## Usage | ||
|
||
To instrument an AWS Lambda function, call the `logfire.instrument_aws_lambda` function after defining | ||
the handler function: | ||
|
||
```python | ||
import logfire | ||
|
||
logfire.configure() # (1)! | ||
|
||
|
||
def handler(event, context): | ||
return 'Hello from Lambda' | ||
|
||
logfire.instrument_aws_lambda(handler) | ||
``` | ||
|
||
1. Remember to set the `LOGFIRE_TOKEN` environment variable on your Lambda function configuration. | ||
|
||
[`logfire.instrument_aws_lambda`][logfire.Logfire.instrument_aws_lambda] uses the **OpenTelemetry AWS Lambda Instrumentation** package, | ||
which you can find more information about [here][opentelemetry-aws-lambda]. | ||
|
||
[opentelemetry-aws-lambda]: https://opentelemetry-python-contrib.readthedocs.io/en/latest/instrumentation/aws_lambda/aws_lambda.html |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
17 changes: 17 additions & 0 deletions
17
logfire-api/logfire_api/_internal/integrations/aws_lambda.pyi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
from opentelemetry.context import Context as Context | ||
from opentelemetry.metrics import MeterProvider | ||
from opentelemetry.trace import TracerProvider | ||
from typing import Any, Callable, TypedDict, Unpack | ||
|
||
LambdaEvent = Any | ||
LambdaFunction = Callable[[LambdaEvent, Any], Any] | ||
|
||
class AwsLambdaInstrumentKwargs(TypedDict, total=False): | ||
skip_dep_check: bool | ||
event_context_extractor: Callable[[LambdaEvent], Context] | ||
|
||
def instrument_aws_lambda(lambda_function: LambdaFunction, *, tracer_provider: TracerProvider, meter_provider: MeterProvider, **kwargs: Unpack[AwsLambdaInstrumentKwargs]) -> None: | ||
"""Instrument the AWS Lambda runtime so that spans are automatically created for each invocation. | ||
|
||
See the `Logfire.instrument_aws_lambda` method for details. | ||
""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
from __future__ import annotations | ||
|
||
from typing import TYPE_CHECKING | ||
|
||
try: | ||
from opentelemetry.context import Context | ||
from opentelemetry.instrumentation.aws_lambda import AwsLambdaInstrumentor | ||
from opentelemetry.metrics import MeterProvider | ||
from opentelemetry.trace import TracerProvider | ||
except ImportError: | ||
raise RuntimeError( | ||
'`logfire.instrument_aws_lambda()` requires the `opentelemetry-instrumentation-aws-lambda` package.\n' | ||
'You can install this with:\n' | ||
" pip install 'logfire[aws-lambda]'" | ||
) | ||
|
||
if TYPE_CHECKING: | ||
from typing import Any, Callable, TypedDict, Unpack | ||
|
||
LambdaEvent = Any | ||
LambdaFunction = Callable[[LambdaEvent, Any], Any] | ||
|
||
class AwsLambdaInstrumentKwargs(TypedDict, total=False): | ||
skip_dep_check: bool | ||
event_context_extractor: Callable[[LambdaEvent], Context] | ||
|
||
|
||
def instrument_aws_lambda( | ||
lambda_function: LambdaFunction, | ||
*, | ||
tracer_provider: TracerProvider, | ||
meter_provider: MeterProvider, | ||
**kwargs: Unpack[AwsLambdaInstrumentKwargs], | ||
) -> None: | ||
"""Instrument the AWS Lambda runtime so that spans are automatically created for each invocation. | ||
|
||
See the `Logfire.instrument_aws_lambda` method for details. | ||
""" | ||
return AwsLambdaInstrumentor().instrument( # type: ignore[no-any-return] | ||
tracer_provider=tracer_provider, meter_provider=meter_provider, **kwargs | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
from __future__ import annotations | ||
|
||
import importlib | ||
from dataclasses import dataclass | ||
from typing import Any | ||
from unittest import mock | ||
|
||
import pytest | ||
from inline_snapshot import snapshot | ||
from opentelemetry.instrumentation.aws_lambda import _HANDLER # type: ignore[import] | ||
|
||
import logfire | ||
import logfire._internal.integrations.aws_lambda | ||
import logfire._internal.integrations.pymongo | ||
from logfire.testing import TestExporter | ||
|
||
|
||
def lambda_handler(event: Any, context: MockLambdaContext): | ||
pass | ||
|
||
|
||
# The below mock is based on the following code: | ||
# https://github.com/open-telemetry/opentelemetry-python-contrib/blob/ecf5529f99222e7d945eddcaa83acb8a47c9ba42/instrumentation/opentelemetry-instrumentation-aws-lambda/tests/test_aws_lambda_instrumentation_manual.py#L57-L66 | ||
@dataclass | ||
class MockLambdaContext: | ||
aws_request_id: str | ||
invoked_function_arn: str | ||
|
||
|
||
def test_instrument_aws_lambda(exporter: TestExporter) -> None: | ||
with mock.patch.dict('os.environ', {_HANDLER: 'tests.otel_integrations.test_aws_lambda.lambda_handler'}): | ||
logfire.instrument_aws_lambda(lambda_handler) | ||
|
||
context = MockLambdaContext( | ||
aws_request_id='mock_aws_request_id', | ||
invoked_function_arn='arn:aws:lambda:us-east-1:123456:function:myfunction:myalias', | ||
) | ||
lambda_handler({'key': 'value'}, context) | ||
|
||
assert exporter.exported_spans_as_dict() == snapshot( | ||
[ | ||
{ | ||
'name': 'tests.otel_integrations.test_aws_lambda.lambda_handler', | ||
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False}, | ||
'parent': None, | ||
'start_time': 1000000000, | ||
'end_time': 2000000000, | ||
'attributes': { | ||
'logfire.span_type': 'span', | ||
'logfire.msg': 'tests.otel_integrations.test_aws_lambda.lambda_handler', | ||
'cloud.resource_id': 'arn:aws:lambda:us-east-1:123456:function:myfunction:myalias', | ||
'faas.invocation_id': 'mock_aws_request_id', | ||
'cloud.account.id': '123456', | ||
}, | ||
} | ||
] | ||
) | ||
|
||
|
||
def test_missing_opentelemetry_dependency() -> None: | ||
with mock.patch.dict('sys.modules', {'opentelemetry.instrumentation.aws_lambda': None}): | ||
with pytest.raises(RuntimeError) as exc_info: | ||
importlib.reload(logfire._internal.integrations.aws_lambda) | ||
assert str(exc_info.value) == snapshot("""\ | ||
`logfire.instrument_aws_lambda()` requires the `opentelemetry-instrumentation-aws-lambda` package. | ||
You can install this with: | ||
pip install 'logfire[aws-lambda]'\ | ||
""") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The examples on AWS use the
lambda_function
name for the function, I prefer to use the same name.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://docs.aws.amazon.com/lambda/latest/dg/python-handler.html
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ah yeah,
lambda_handler
, notlambda_function
. mbThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Anything else in this PR besides this? I'll merge after fixing this otherwise.