2

In order to log to cloudwatch in a lambda, one must use this log4j2.xml:

<?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>

Also the following items must be in the pom.xml:

 <parent>
    <artifactId>spring-boot-starter-parent</artifactId>
    <groupId>org.springframework.boot</groupId>
    <version>2.1.5.RELEASE</version>
  </parent>
...
    <dependency>
      <artifactId>aws-lambda-java-log4j2</artifactId>
      <groupId>com.amazonaws</groupId>
      <version>1.1.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.11.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.11.2</version>
    </dependency>

Of course none of this works for me. It seems Spring uses Logback and I have tried shutting that off using these instructions. Nothing seems to work.

Any tips?

markthegrea
  • 3,731
  • 7
  • 55
  • 78

1 Answers1

2

Got it! I read a post/rant where a guy noticed that AWS used a "5 year old jar" for the Cloudwatch/Lambda logging (can't find it now). So I found a Log4j2 jar that is compatible with 1.2 (log4j-1.2-api) and it worked. I had to shut off Logback in Spring and activate Log4j2. Below should take you all the way.

       <dependency>
          <artifactId>spring-boot-starter</artifactId>
          <groupId>org.springframework.boot</groupId>
          <exclusions>
            <exclusion>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
          </exclusions>
        </dependency>
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
        <dependency>
          <artifactId>aws-lambda-java-log4j2</artifactId>
          <groupId>com.amazonaws</groupId>
          <version>1.1.0</version>
        </dependency>

        <dependency>
          <groupId>org.apache.logging.log4j</groupId>
          <artifactId>log4j-core</artifactId>
          <version>2.11.2</version>
        </dependency>
        <dependency>
          <groupId>org.apache.logging.log4j</groupId>
          <artifactId>log4j-1.2-api</artifactId>
          <version>2.11.2</version>
        </dependency>
...

PS. You might need to fix this as well: log4j2 ERROR StatusLogger Unrecognized conversion specifier

markthegrea
  • 3,731
  • 7
  • 55
  • 78