简体   繁体   中英

How to get Context for logging when using APIGatewayProxyRequestEvent in aws-lambda

My project is written in spring-cloud-function and deployed in aws-lambda. I have a requirement wherein I am supposed to log the events.

A little search told me to use

com.amazonaws.services.lambda.runtime.Context for logging by doing this:

context.getLogger().log("log event here");

I have a spring cloud function which receives APIGatewayProxyRequestEvent as the input and APIGatewayProxyResponseEvent as the output parameter

I searched again and found to get the context, this can be wrapped with org.springframework.messaging.Message

so I wrote the function like this:

public Function<Message<APIGatewayProxyRequestEvent>, APIGatewayProxyResponseEvent> saveEmployee(){
return request -> {
            Context context = request.getHeaders().get("aws-context", Context.class);
context.getLogger().log("employee save request---: " + request);
    //do something

However the context evaluates to null and I get NullPointerException

Can someone point to what might be going wrong? or how to fetch context?

Thanks in advance

Make sure to use the following handler: org.springframework.cloud.function.adapter.aws.FunctionInvoker::handleRequest

You can implement the RequestHandler class and oveeride handleRequest method. The context parameter can be used to enter logs for cloudwatch.

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;

public class Function implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent>  {

@Override
    public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent event, final Context context) {

LambdaLogger logger = context.getLogger();
logger.log(event);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM