
Logging
Logging for an AWS Lambda Java function can easily be set up with it. Logging helps to trace execution paths and troubleshoot issues, and generally, it provides insight on how the code is behaving.
Each statement to log creates an AWS CloudWatch event. You can find the logs in the console. Also, for the synchronous execution of functions via the Lambda console, one can find the logs right there.
There are two methods for having a logging solution set up in your AWS Lambda code, as follows:
- Using Log4j2: Log4j2 is a widely used logging library, used in the JVM world. To configure logging for the Lambda function using Log4j2, the following settings are required.
It will require the following artifacts on the classpath of the deployment package:
com.amazonaws:aws-lambda-java-log4j2:1.0.0
org.apache.logging.log4j:log4j-core:2.8.2
org.apache.logging.log4j:log4j-api:2.8.2
You will have to configure the handler as follows:
package example;
import com.amazonaws.services.lambda.runtime.Context;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Hello {
// Initialize the Log4j logger
static final Logger logger = LogManager.getLogger(Hello.class);
logger.info("info event");
logger.debug("debug event");
}
Log4j requires a log4j2.xml with the logging configuration as a part of the classpath in the package as well. A sample configuration, taken from the official AWS literature, is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration packages="com.amazonaws.services.lambda.runtime.log4j2.LambdaAppender">
<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="debug">
<AppenderRef ref="Lambda" />
</Root>
</Loggers>
</Configuration>
- Using LambdaLogger(): LambdaLogger is a property of the context object, passed to the Lambda handler function as the second argument.
A developer can choose to use this turnkey solution without configuring a Log4j2 setup, as described in the previous example.
An example of using the solution is as follows:
package example;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class Hello {
public String myHandler(String name, Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Logged from the LambdaLogger);
}
}
Log Generator: Code statements that generate log entries in the CloudWatch repository or in the console are as follows:
//Standard output
System.out.Println()
//Standard error
System.err.Println()
//Lambda Logger
Logger.log()
//Log4j2 info
log.info()
//log4j2 debug
log.debug()
//log4j2 errir
log.error()