Search code examples
javaspring-bootlogbackamazon-cloudwatch

AWS Cloudwatch Logback Appender for Spring Boot Applications


I'm trying to send Logs directly to Cloudwatch from my Spring Boot Application. The Logback Appender I'm using, of course needs AWS Credentials. Since most developers doesn't have AWS Credentials on their local machines and just want to log into a file according to the the logback-spring.xml configuration. Most tests fail locally, because of missing aws credentials.
Is there a way to initialize the logback appender only for a specific profile?
Here's a snapshot of the logback-spring.xml:

<!--  Configuration for your local environment -->
<springProfile name="${user.name}">
    <root level="DEBUG">
        <appender-ref ref="ROLLING_FILE" />
    </root>
</springProfile>

<appender name="ROLLING_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    ...
</appender>


<!-- Configuration for Development Environment --> 
<springProfile name="dev">
    <root level="DEBUG">
        <appender-ref ref="AWS_LOGS_DEV" />
        <appender-ref ref="ROLLING_FILE" />
    </root>
</springProfile>

<appender name="AWS_LOGS_DEV" class="ca.pjer.logback.AwsLogsAppender">
    <layout>
        <pattern>${FILE_LOG_PATTERN}</pattern>
    </layout>
    <logGroupName>/dev</logGroupName>
    <logStreamName>log_${date}</logStreamName>
</appender>

Solution

  • Already solved. You just need to extract the appender to another logback-file:

    logback-spring.xml

    <!--  Configuration for your local environment -->
    <springProfile name="${user.name}">
        <root level="DEBUG">
            <appender-ref ref="ROLLING_FILE" />
        </root>
    </springProfile>
    
    <appender name="ROLLING_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        ...
    </appender>
    
    
    <!-- Configuration for Environment in AWS, extracted into its own logback-prod.xml file--> 
    <springProfile name="prod">
        <include resource="logback-prod.xml" />
    </springProfile>
    

    logback-prod.xml

    <included>
        <root level="DEBUG">
            <appender-ref ref="AWS_LOGS_DEV" />
            <appender-ref ref="ROLLING_FILE" />
        </root>
        
        <shutdownHook class="ch.qos.logback.core.hook.DelayingShutdownHook"/>
        <appender name="AWS_LOGS_DEV" class="ca.pjer.logback.AwsLogsAppender">
            <layout>
                <pattern>${FILE_LOG_PATTERN}</pattern>
            </layout>
            <logGroupName>/prod</logGroupName>
            <logStreamName>log_${date}</logStreamName>
            <maxBatchLogEvents>200</maxBatchLogEvents>
            <maxFlushTimeMillis>30000</maxFlushTimeMillis>
            <maxBlockTimeMillis>5000</maxBlockTimeMillis>
        </appender>
    </included>