

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 Lambda 內容物件擷取 Python 函數資訊
<a name="python-context"></a>

當 Lambda 執行您的函數時，它會將內容物件傳遞至[處理常式](python-handler.md)。此物件提供的方法和各項屬性提供了有關調用、函式以及執行環境的資訊。如需如何將內容物件傳遞至函數處理常式的詳細資訊，請參閱[以 Python 定義 Lambda 函數處理常式](python-handler.md)。

**內容方法**
+ `get_remaining_time_in_millis` - 傳回執行逾時前剩餘的毫秒數。

**內容屬性**
+ `function_name` – Lambda 函數的名稱。
+ `function_version` – 函數的[版本](configuration-versions.md)。
+ `invoked_function_arn` - 用於叫用此函數的 Amazon Resource Name (ARN)。指出調用者是否指定版本號或別名。
+ `memory_limit_in_mb` - 分配給函數的記憶體數量。
+ `aws_request_id` - 調用請求的識別符。
+ `log_group_name` - 函數的日誌群組。
+ `log_stream_name` - 函數執行個體的記錄串流。
+ `identity` - (行動應用程式) 已授權請求的 Amazon Cognito 身分的相關資訊。
  + `cognito_identity_id` - 已驗證的 Amazon Cognito 身分。
  + `cognito_identity_pool_id` - 授權調用的 Amazon Cognito 身分集區。
+ `client_context` - (行動應用程式) 用戶端應用程式提供給 Lambda 的用戶端內容。
  + `client.installation_id`
  + `client.app_title`
  + `client.app_version_name`
  + `client.app_version_code`
  + `client.app_package_name`
  + `custom` - 行動用戶端應用程式所設定的 `dict` 自訂值。
  + `env` - AWS 開發套件所提供的 `dict` 環境資訊。

Powertools for Lambda (Python) 提供了 Lambda 內容物件的介面定義。您可以使用介面定義作為類型提示，或進一步檢查 Lambda 內容物件的結構。如需介面定義，請參閱 GitHub 上的 *powertools-lambda-python* 儲存庫中的 [lambda\$1context.py](https://github.com/aws-powertools/powertools-lambda-python/blob/develop/aws_lambda_powertools/utilities/typing/lambda_context.py)。

以下範例顯示記錄著內容資訊的處理常式函式。

**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())
```

除了上面所列的選項，您也可以將 AWS X-Ray 開發套件用於 [在 中檢測 Python 程式碼 AWS Lambda](python-tracing.md)，識別重要的程式碼路徑，追蹤它們的效能，並且擷取要進行分析的資料。