Java 我的CloudWatch日志中缺少AWSRequestId
我在Java8中使用AWS Lambda,在CloudWatch中使用Log4j2记录器打印日志,下面是我的Log4j2配置Java 我的CloudWatch日志中缺少AWSRequestId,java,aws-lambda,aws-sdk,amazon-cloudwatch,Java,Aws Lambda,Aws Sdk,Amazon Cloudwatch,我在Java8中使用AWS Lambda,在CloudWatch中使用Log4j2记录器打印日志,下面是我的Log4j2配置 <?xml version="1.0" encoding="UTF-8"?> <Configuration packages="com.amazonaws.services.lambda.runtime.log4j2"> <Appenders> <Lambda name="Lambda">
<?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>
当我们使用Log4j进行日志记录时,我们通过在抽象Lambda处理程序类的Log4jThreadContext中添加AWSRequestId解决了这个问题。因此,每当lambda函数获取触发器时,它都会在ThreadContext映射中添加AWSRequestId,并在打印日志时可用
这里有一个关于Log4j线程上下文映射的链接->
/**
*所有lambda处理程序类都应该扩展这个类。
*/
公共抽象类AbstractEventHandler实现RequestHandler{
@凌驾
公共O handleRequest(I输入,上下文){
//在我们的实现中,我们已经从主线程创建了子线程
//但在子线程中,线程上下文映射可能不可用。
//所以我们需要通过设置Log4j属性来传递它
//isThreadContextMapInheritable为true。
setProperty(“isThreadContextMapInheritable”、“true”);
//在ThreadContext映射中添加AWSRequestId。
put(“AWSRequestId”,context.getAwsRequestId());
返回requestHandler(输入、上下文);
}
抽象受保护的O请求处理程序(I输入,上下文);
}
当我们使用Log4j进行日志记录时,我们通过在抽象Lambda处理程序类的Log4jThreadContext中添加AWSRequestId解决了这个问题。因此,每当lambda函数获取触发器时,它都会在ThreadContext映射中添加AWSRequestId,并在打印日志时可用
这里有一个关于Log4j线程上下文映射的链接->
/**
*所有lambda处理程序类都应该扩展这个类。
*/
公共抽象类AbstractEventHandler实现RequestHandler{
@凌驾
公共O handleRequest(I输入,上下文){
//在我们的实现中,我们已经从主线程创建了子线程
//但在子线程中,线程上下文映射可能不可用。
//所以我们需要通过设置Log4j属性来传递它
//isThreadContextMapInheritable为true。
setProperty(“isThreadContextMapInheritable”、“true”);
//在ThreadContext映射中添加AWSRequestId。
put(“AWSRequestId”,context.getAwsRequestId());
返回requestHandler(输入、上下文);
}
抽象受保护的O请求处理程序(I输入,上下文);
}
/**
* 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);
}