Using the Lambda context object to retrieve Python function information
When Lambda runs your function, it passes a context object to the handler. This object provides methods and properties that provide information about the invocation, function, and execution environment. For more information on how the context object is passed to the function handler, see Define Lambda function handler in Python.
Context methods
-
get_remaining_time_in_millisโ Returns the number of milliseconds left before the execution times out.
Context properties
-
function_nameโ The name of the Lambda function. -
function_versionโ The version of the function. -
invoked_function_arnโ The Amazon Resource Name (ARN) that's used to invoke the function. Indicates if the invoker specified a version number or alias. -
memory_limit_in_mbโ The amount of memory that's allocated for the function. -
aws_request_idโ The identifier of the invocation request. -
log_group_nameโ The log group for the function. -
log_stream_nameโ The log stream for the function instance. -
identityโ (mobile apps) Information about the Amazon Cognito identity that authorized the request.-
cognito_identity_idโ The authenticated Amazon Cognito identity. -
cognito_identity_pool_idโ The Amazon Cognito identity pool that authorized the invocation.
-
-
client_contextโ (mobile apps) Client context that's provided to Lambda by the client application.-
client.installation_id -
client.app_title -
client.app_version_name -
client.app_version_code -
client.app_package_name -
customโ Adictof custom values set by the mobile client application. -
envโ Adictof environment information provided by the AWS SDK.
-
Powertools for Lambda (Python) provides an interface definition for the Lambda context object. You can use the interface
definition for type hints, or to further inspect the structure of the Lambda context object. For the interface
definition, see lambda_context.py
The following example shows a handler function that logs context information.
Example handler.py
import time def lambda_handler(event, context): print("Lambda function ARN:", context.invoked_function_arn) print("CloudWatch log stream name:", context.log_stream_name) print("CloudWatch log group name:", context.log_group_name) print("Lambda Request ID:", context.aws_request_id) print("Lambda function memory limits in MB:", context.memory_limit_in_mb) # We have added a 1 second delay so you can see the time remaining in get_remaining_time_in_millis. time.sleep(1) print("Lambda time remaining in MS:", context.get_remaining_time_in_millis())
In addition to the options listed above, you can also use the AWS X-Ray SDK for Instrumenting Python code in AWS Lambda to identify critical code paths, trace their performance and capture the data for analysis.