diff --git a/example/HelloWorldFunction/pom.xml b/example/HelloWorldFunction/pom.xml
new file mode 100644
index 000000000..0826d8884
--- /dev/null
+++ b/example/HelloWorldFunction/pom.xml
@@ -0,0 +1,75 @@
+
+ 4.0.0
+ helloworld
+ HelloWorld
+ 1.0
+ jar
+ A sample Hello World created for SAM CLI.
+
+ 1.8
+ 1.8
+ 2.13.2
+
+
+
+
+ software.aws.lambda
+ aws-lambda-powertools-java
+ 0.1.0-SNAPSHOT
+
+
+ com.amazonaws
+ aws-lambda-java-core
+ 1.2.0
+
+
+ com.amazonaws
+ aws-lambda-java-events
+ 3.1.0
+
+
+
+ org.apache.logging.log4j
+ log4j-core
+ ${log4j.version}
+
+
+ org.apache.logging.log4j
+ log4j-api
+ ${log4j.version}
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ 2.9.3
+
+
+
+ junit
+ junit
+ 4.12
+ test
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-shade-plugin
+ 3.1.1
+
+
+
+
+ package
+
+ shade
+
+
+
+
+
+
+
diff --git a/example/HelloWorldFunction/src/main/java/helloworld/App.java b/example/HelloWorldFunction/src/main/java/helloworld/App.java
new file mode 100644
index 000000000..51d64ad6e
--- /dev/null
+++ b/example/HelloWorldFunction/src/main/java/helloworld/App.java
@@ -0,0 +1,56 @@
+package helloworld;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import com.amazonaws.services.lambda.runtime.Context;
+import com.amazonaws.services.lambda.runtime.RequestHandler;
+import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
+import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import software.aws.lambda.logging.LambdaJsonAppender;
+
+/**
+ * Handler for requests to Lambda function.
+ */
+public class App implements RequestHandler {
+
+ Logger log = LogManager.getLogger();
+
+ public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) {
+ LambdaJsonAppender.loadContextKeys(context);
+
+ Map headers = new HashMap<>();
+ headers.put("Content-Type", "application/json");
+ headers.put("X-Custom-Header", "application/json");
+
+ APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent()
+ .withHeaders(headers);
+ try {
+ final String pageContents = this.getPageContents("https://checkip.amazonaws.com");
+ log.info(pageContents);
+ String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents);
+
+ return response
+ .withStatusCode(200)
+ .withBody(output);
+ } catch (IOException e) {
+ return response
+ .withBody("{}")
+ .withStatusCode(500);
+ }
+ }
+
+ private String getPageContents(String address) throws IOException{
+ URL url = new URL(address);
+ try(BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
+ return br.lines().collect(Collectors.joining(System.lineSeparator()));
+ }
+ }
+}
diff --git a/example/HelloWorldFunction/src/main/resources/log4j2.xml b/example/HelloWorldFunction/src/main/resources/log4j2.xml
new file mode 100644
index 000000000..898f77f7f
--- /dev/null
+++ b/example/HelloWorldFunction/src/main/resources/log4j2.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/example/README.md b/example/README.md
new file mode 100644
index 000000000..e5300c6e7
--- /dev/null
+++ b/example/README.md
@@ -0,0 +1,120 @@
+# sam-app
+
+This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders.
+
+- HelloWorldFunction/src/main - Code for the application's Lambda function.
+- events - Invocation events that you can use to invoke the function.
+- HelloWorldFunction/src/test - Unit tests for the application code.
+- template.yaml - A template that defines the application's AWS resources.
+
+The application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code.
+
+If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit.
+The AWS Toolkit is an open source plug-in for popular IDEs that uses the SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started.
+
+* [PyCharm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
+* [IntelliJ](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
+* [VS Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html)
+* [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html)
+
+## Deploy the sample application
+
+The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API.
+
+To use the SAM CLI, you need the following tools.
+
+* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)
+* Java8 - [Install the Java SE Development Kit 8](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)
+* Maven - [Install Maven](https://maven.apache.org/install.html)
+* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community)
+
+To build and deploy your application for the first time, run the following in your shell:
+
+```bash
+sam build
+sam deploy --guided
+```
+
+The first command will build the source of your application. The second command will package and deploy your application to AWS, with a series of prompts:
+
+* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name.
+* **AWS Region**: The AWS region you want to deploy your app to.
+* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes.
+* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modified IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command.
+* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application.
+
+You can find your API Gateway Endpoint URL in the output values displayed after deployment.
+
+## Use the SAM CLI to build and test locally
+
+Build your application with the `sam build` command.
+
+```bash
+sam-app$ sam build
+```
+
+The SAM CLI installs dependencies defined in `HelloWorldFunction/pom.xml`, creates a deployment package, and saves it in the `.aws-sam/build` folder.
+
+Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project.
+
+Run functions locally and invoke them with the `sam local invoke` command.
+
+```bash
+sam-app$ sam local invoke HelloWorldFunction --event events/event.json
+```
+
+The SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000.
+
+```bash
+sam-app$ sam local start-api
+sam-app$ curl http://localhost:3000/
+```
+
+The SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path.
+
+```yaml
+ Events:
+ HelloWorld:
+ Type: Api
+ Properties:
+ Path: /hello
+ Method: get
+```
+
+## Add a resource to your application
+The application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as functions, triggers, and APIs. For resources not included in [the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types.
+
+## Fetch, tail, and filter Lambda function logs
+
+To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug.
+
+`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM.
+
+```bash
+sam-app$ sam logs -n HelloWorldFunction --stack-name sam-app --tail
+```
+
+You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html).
+
+## Unit tests
+
+Tests are defined in the `HelloWorldFunction/src/test` folder in this project.
+
+```bash
+sam-app$ cd HelloWorldFunction
+HelloWorldFunction$ mvn test
+```
+
+## Cleanup
+
+To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following:
+
+```bash
+aws cloudformation delete-stack --stack-name sam-app
+```
+
+## Resources
+
+See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts.
+
+Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/)
diff --git a/example/events/event.json b/example/events/event.json
new file mode 100644
index 000000000..3822fadaa
--- /dev/null
+++ b/example/events/event.json
@@ -0,0 +1,63 @@
+{
+ "body": "{\"message\": \"hello world\"}",
+ "resource": "/{proxy+}",
+ "path": "/path/to/resource",
+ "httpMethod": "POST",
+ "isBase64Encoded": false,
+ "queryStringParameters": {
+ "foo": "bar"
+ },
+ "pathParameters": {
+ "proxy": "/path/to/resource"
+ },
+ "stageVariables": {
+ "baz": "qux"
+ },
+ "headers": {
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
+ "Accept-Encoding": "gzip, deflate, sdch",
+ "Accept-Language": "en-US,en;q=0.8",
+ "Cache-Control": "max-age=0",
+ "CloudFront-Forwarded-Proto": "https",
+ "CloudFront-Is-Desktop-Viewer": "true",
+ "CloudFront-Is-Mobile-Viewer": "false",
+ "CloudFront-Is-SmartTV-Viewer": "false",
+ "CloudFront-Is-Tablet-Viewer": "false",
+ "CloudFront-Viewer-Country": "US",
+ "Host": "1234567890.execute-api.us-east-1.amazonaws.com",
+ "Upgrade-Insecure-Requests": "1",
+ "User-Agent": "Custom User Agent String",
+ "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)",
+ "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==",
+ "X-Forwarded-For": "127.0.0.1, 127.0.0.2",
+ "X-Forwarded-Port": "443",
+ "X-Forwarded-Proto": "https"
+ },
+ "requestContext": {
+ "accountId": "123456789012",
+ "resourceId": "123456",
+ "stage": "prod",
+ "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
+ "requestTime": "09/Apr/2015:12:34:56 +0000",
+ "requestTimeEpoch": 1428582896000,
+ "identity": {
+ "cognitoIdentityPoolId": null,
+ "accountId": null,
+ "cognitoIdentityId": null,
+ "caller": null,
+ "accessKey": null,
+ "sourceIp": "127.0.0.1",
+ "cognitoAuthenticationType": null,
+ "cognitoAuthenticationProvider": null,
+ "userArn": null,
+ "userAgent": "Custom User Agent String",
+ "user": null
+ },
+ "path": "/prod/path/to/resource",
+ "resourcePath": "/{proxy+}",
+ "httpMethod": "POST",
+ "apiId": "1234567890",
+ "protocol": "HTTP/1.1"
+ }
+ }
+
\ No newline at end of file
diff --git a/example/template.yaml b/example/template.yaml
new file mode 100644
index 000000000..40d9e13f3
--- /dev/null
+++ b/example/template.yaml
@@ -0,0 +1,43 @@
+AWSTemplateFormatVersion: '2010-09-09'
+Transform: AWS::Serverless-2016-10-31
+Description: >
+ sam-app
+
+ Sample SAM Template for sam-app
+
+# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
+Globals:
+ Function:
+ Timeout: 20
+
+Resources:
+ HelloWorldFunction:
+ Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
+ Properties:
+ CodeUri: HelloWorldFunction
+ Handler: helloworld.App::handleRequest
+ Runtime: java8
+ MemorySize: 512
+ Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
+ Variables:
+ PARAM1: VALUE
+ Events:
+ HelloWorld:
+ Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
+ Properties:
+ Path: /hello
+ Method: get
+
+Outputs:
+ # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
+ # Find out more about other implicit resources you can reference within SAM
+ # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
+ HelloWorldApi:
+ Description: "API Gateway endpoint URL for Prod stage for Hello World function"
+ Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
+ HelloWorldFunction:
+ Description: "Hello World Lambda Function ARN"
+ Value: !GetAtt HelloWorldFunction.Arn
+ HelloWorldFunctionIamRole:
+ Description: "Implicit IAM Role created for Hello World function"
+ Value: !GetAtt HelloWorldFunctionRole.Arn
diff --git a/pom.xml b/pom.xml
index eadf395d7..19d0b367f 100644
--- a/pom.xml
+++ b/pom.xml
@@ -39,6 +39,9 @@
1.8
1.8
+ 2.13.2
+ 2.11.0
+ UTF-8
@@ -53,6 +56,35 @@
+
+ com.amazonaws
+ aws-lambda-java-core
+ 1.2.1
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ ${jackson.version}
+
+
+
+
+ org.projectlombok
+ lombok
+ 1.18.12
+ provided
+
+
+ org.apache.logging.log4j
+ log4j-core
+ ${log4j.version}
+
+
+ org.apache.logging.log4j
+ log4j-api
+ ${log4j.version}
+
+
org.junit.jupiter
junit-jupiter-api
diff --git a/src/main/java/software/aws/lambda/logging/LambdaJsonAppender.java b/src/main/java/software/aws/lambda/logging/LambdaJsonAppender.java
new file mode 100644
index 000000000..0a8566c15
--- /dev/null
+++ b/src/main/java/software/aws/lambda/logging/LambdaJsonAppender.java
@@ -0,0 +1,110 @@
+package software.aws.lambda.logging;
+
+import com.amazonaws.services.lambda.runtime.Context;
+import com.amazonaws.services.lambda.runtime.LambdaRuntime;
+import com.amazonaws.services.lambda.runtime.LambdaRuntimeInternal;
+import com.amazonaws.services.lambda.runtime.LambdaLogger;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.logging.log4j.core.Filter;
+import org.apache.logging.log4j.core.Layout;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
+import org.apache.logging.log4j.core.config.plugins.Plugin;
+import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
+
+import java.io.Serializable;
+
+@Plugin(name = LambdaJsonAppender.PLUGIN_NAME, category = LambdaJsonAppender.PLUGIN_CATEGORY,
+ elementType = LambdaJsonAppender.PLUGIN_TYPE, printObject = true)
+public class LambdaJsonAppender extends AbstractAppender {
+
+ private static final String serviceName = System.getProperty("POWERTOOLS_SERVICE_NAME", "service_undefined");
+
+ public static final String PLUGIN_NAME = "LambdaJsonAppender";
+ public static final String PLUGIN_CATEGORY = "Core";
+ public static final String PLUGIN_TYPE = "appender";
+ private static String functionName;
+ private static String functionVersion;
+ private static String functionArn;
+ private static String functionRequestId;
+ private static int functionMemorySize;
+
+ private final LambdaLogger logger = LambdaRuntime.getLogger();
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+ /**
+ * Builder class that follows log4j2 plugin convention
+ * @param Generic Builder class
+ */
+ public static class Builder> extends AbstractAppender.Builder
+ implements org.apache.logging.log4j.core.util.Builder {
+
+ /**
+ * creates a new LambdaAppender
+ * @return a new LambdaAppender
+ */
+ public LambdaJsonAppender build() {
+ return new LambdaJsonAppender(super.getName(), super.getFilter(), super.getOrCreateLayout(),
+ super.isIgnoreExceptions());
+ }
+ }
+
+ /**
+ * Method used by log4j2 to access this appender
+ * @param Generic Builder class
+ * @return LambdaAppender Builder
+ */
+ @PluginBuilderFactory
+ public static > B newBuilder() {
+ return new Builder().asBuilder();
+ }
+
+ /**
+ * Constructor method following AbstractAppender convention
+ * @param name name of appender
+ * @param filter filter specified in xml
+ * @param layout layout specified in xml
+ * @param ignoreExceptions whether to show exceptions or not specified in xml
+ */
+ private LambdaJsonAppender(String name, Filter filter, Layout extends Serializable> layout, boolean ignoreExceptions) {
+ super(name, filter, layout, ignoreExceptions);
+ LambdaRuntimeInternal.setUseLog4jAppender(true);
+ }
+
+ /**
+ * Append log event to System.out
+ * @param event log4j event
+ */
+ public void append(LogEvent event) {
+ LogEntry logEntry = LogEntry.builder()
+ .level(event.getLevel().name())
+ .message(event.getMessage().getFormattedMessage())
+ .timestamp(event.getInstant().toString())
+ .functionName(functionName)
+ .functionArn(functionArn)
+ .functionRequestId(functionRequestId)
+ .functionVersion(functionVersion)
+ .functionMemorySize(functionMemorySize)
+ .service(serviceName)
+ .build();
+
+ String eventAsString = null;
+ try {
+ eventAsString = OBJECT_MAPPER.writeValueAsString(logEntry);
+ } catch (JsonProcessingException e) {
+ throw new PowerToolsClientException(e.getMessage());
+ }
+
+ this.logger.log(eventAsString);
+ }
+
+ public static void loadContextKeys(Context context) {
+ functionName = context.getFunctionName();
+ functionVersion = context.getFunctionVersion();
+ functionArn = context.getInvokedFunctionArn();
+ functionRequestId = context.getAwsRequestId();
+ functionMemorySize = context.getMemoryLimitInMB();
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/software/aws/lambda/logging/LogEntry.java b/src/main/java/software/aws/lambda/logging/LogEntry.java
new file mode 100644
index 000000000..061eaa992
--- /dev/null
+++ b/src/main/java/software/aws/lambda/logging/LogEntry.java
@@ -0,0 +1,31 @@
+package software.aws.lambda.logging;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+@Builder
+@JsonIgnoreProperties(ignoreUnknown=true)
+public class LogEntry {
+
+ private String timestamp;
+ private String level;
+ // TODO - MS not sure on the impl here
+// private String location;
+ private String service;
+ private double samplingRate;
+ private String message;
+
+ private String functionName;
+ private String functionVersion;
+ private String functionArn;
+ private int functionMemorySize;
+ private String functionRequestId;
+
+ private boolean coldStart;
+}
\ No newline at end of file
diff --git a/src/main/java/software/aws/lambda/logging/PowerToolsClientException.java b/src/main/java/software/aws/lambda/logging/PowerToolsClientException.java
new file mode 100644
index 000000000..4b1abb954
--- /dev/null
+++ b/src/main/java/software/aws/lambda/logging/PowerToolsClientException.java
@@ -0,0 +1,7 @@
+package software.aws.lambda.logging;
+
+public class PowerToolsClientException extends Error {
+ public PowerToolsClientException(String message) {
+ super(message);
+ }
+}
\ No newline at end of file