C# の AWS Lambda context オブジェクト - AWS Lambda

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

C# の AWS Lambda context オブジェクト

Lambda で関数が実行されると、コンテキストオブジェクトがハンドラーに渡されます。このオブジェクトは、呼び出し、関数、および実行関数に関する情報を含むプロパティです。

context プロパティ
  • FunctionName - Lambda 関数の名前。

  • FunctionVersion - 関数のバージョン

  • InvokedFunctionArn - 関数を呼び出すために使用される Amazon リソースネーム (ARN)。呼び出し元でバージョン番号またはエイリアスが指定されているかどうかを示します。

  • MemoryLimitInMB - 関数に割り当てられたメモリの量。

  • AwsRequestId - 呼び出しリクエストの ID。

  • LogGroupName - 関数のロググループ。

  • LogStreamName - 関数インスタンスのログストリーム。

  • RemainingTime (TimeSpan) - 実行がタイムアウトするまでの残りのミリ秒数。

  • Identity - (モバイルアプリケーション) リクエストを認可した Amazon Cognito ID に関する情報。

  • ClientContext - (モバイルアプリケーション) クライアントアプリケーションが Lambda に提供したクライアントコンテキスト。

  • Logger 関数のロガーオブジェクト

モニタリング目的として、ILambdaContext オブジェクトの情報を使用して関数の呼び出しに関する情報を出力できます。次のコードは、構造化ログ記録フレームワークにコンテキスト情報を追加する方法の例を示しています。この例では、関数はログ出力に AwsRequestId を追加します。また、この関数は RemainingTime プロパティを使用して、Lambda 関数のタイムアウトに達しそうな場合にインフライトタスクをキャンセルします。

[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace GetProductHandler; public class Function { private readonly IDatabaseRepository _repo; public Function() { this._repo = new DatabaseRepository(); } public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context) { Logger.AppendKey("AwsRequestId", context.AwsRequestId); var id = request.PathParameters["id"]; using var cts = new CancellationTokenSource(); try { cts.CancelAfter(context.RemainingTime.Add(TimeSpan.FromSeconds(-1))); var databaseRecord = await this._repo.GetById(id, cts.Token); return new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = JsonSerializer.Serialize(databaseRecord) }; } finally { cts.Cancel(); return new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.InternalServerError, Body = JsonSerializer.Serialize(databaseRecord) }; } } }