

# 使用 Lambda 上下文对象检索 C\$1 函数信息
<a name="csharp-context"></a>

Lambda 运行您的函数时，会将 context 对象传递到[处理程序](csharp-handler.md)。此对象提供的属性包含有关调用、函数和执行环境的信息。

**上下文属性**
+ `FunctionName` – Lambda 函数的名称。
+ `FunctionVersion` – 函数的[版本](configuration-versions.md)
+ `InvokedFunctionArn` – 用于调用函数的 Amazon Resource Name (ARN)。表明调用者是否指定了版本号或别名。
+ `MemoryLimitInMB` – 为函数分配的内存量。
+ `AwsRequestId` – 调用请求的标识符。
+ `LogGroupName` – 函数的日志组。
+ `LogStreamName` – 函数实例的日志流。
+ `RemainingTime` (`TimeSpan`) – 执行超时前剩余的毫秒数。
+ `Identity` – （移动应用程序）授权请求的 Amazon Cognito 身份的相关信息。
+ `ClientContext` – （移动应用程序）客户端应用程序提供给 Lambda 的客户端上下文。
+ `Logger` 函数的[记录器对象](csharp-logging.md)。

您可以使用 `ILambdaContext` 对象中的信息输出有关函数调用的信息，以便进行监控。以下代码提供了如何向结构化日志记录框架添加上下文信息的示例。在此示例中，该函数将 `AwsRequestId` 添加到日志输出中。如果即将到达 Lambda 函数超时，该函数还使用 `RemainingTime` 属性取消正在进行的任务。

```
[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)
            };
        }
        catch (Exception ex)
        {
            return new APIGatewayProxyResponse 
            {
                StatusCode = (int)HttpStatusCode.InternalServerError,
                Body = JsonSerializer.Serialize(new { error = ex.Message })
            };
        }
        finally
        {
            cts.Cancel();
        }
    }
}
```