pramesh
pramesh

Reputation: 531

AWSRequestId is missing from my CloudWatch logs

I am using AWS Lambda with Java 8, and I am using Log4j2 Logger for printing logs in CloudWatch, following is my Log4j2 configuration.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration packages="com.amazonaws.services.lambda.runtime.log4j2">
    <Appenders>
        <Lambda name="Lambda">
            <PatternLayout>
                <pattern>%d{yyyy-MM-dd HH:mm:ss} %X{AWSRequestId} %-5p %c{1}:%L - %m%n</pattern>
            </PatternLayout>
        </Lambda>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Lambda"/>
        </Root>
    </Loggers>
</Configuration>

But CloudWatch is not printing AWSRequestId, as you can see in the following image, it looks like, if request ID is missing, then it is missing for all the logs for that request, and if the request ID shows up, it shows up for all the logs for that request (inside red box).

enter image description here

Upvotes: 2

Views: 3100

Answers (1)

pramesh
pramesh

Reputation: 531

As we were using Log4j for logging, we fixed this issue by adding AWSRequestId in Log4j ThreadContext in our abstract Lambda handler class. So whenever lambda function gets triggers, it add AWSRequestId in ThreadContext map and is available while printing log.

Here is a link about Log4j ThreadContext map -> https://logging.apache.org/log4j/2.x/manual/thread-context.html

/**
 * All the lambda handler class should extend this class.
 */
public abstract class AbstractEventHandler<I, O> implements RequestHandler<I, O> {

    @Override
    public O handleRequest(I input, Context context) {
        // As in our implementation, we have created child threads from our main thread
        // but in child threads, Thread ContextMap might not be available.
        // so we need to pass this by setting Log4j property
        // isThreadContextMapInheritable to true.
        System.setProperty("isThreadContextMapInheritable", "true");

        // Adding AWSRequestId in ThreadContext map.
        ThreadContext.put("AWSRequestId", context.getAwsRequestId());
        return requestHandler(input, context);
    }

    abstract protected O requestHandler(I input, Context context);
}

Upvotes: 1

Related Questions