com.networknt.aws.lambda.AwsLambdaAppender Maven / Gradle / Ivy
/*
 * jlib - Open Source Java Library
 *
 *     www.jlib.org
 *
 *
 *     Copyright 2005-2018 Igor Akkerman
 *
 *     Licensed under the Apache License, Version 2.0 (the "License");
 *     you may not use this file except in compliance with the License.
 *     You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS,
 *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *     See the License for the specific language governing permissions and
 *     limitations under the License.
 */
package com.networknt.aws.lambda;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.LambdaRuntime;
import com.amazonaws.services.lambda.runtime.LambdaRuntimeInternal;
import org.slf4j.MDC;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import ch.qos.logback.core.encoder.Encoder;
/**
 * Logback {@link Appender}
 * to be used in AWS Lambda applications,
 * targeting CloudWatch Logs.
 * 
 * Instead of writing to the standard output, this {@link Appender} passes the messages to {@link LambdaLogger}.
 * This allows to avoid issues with exception stacktraces or other messages spanning across multiple lines.
 * 
 * This {@link Appender} ensures that Logback's {@link MDC} contains the AWSRequestId, which can be added to the log pattern.
 * 
 * Example XML configuration:
 * 
{@code 
 *
 *     
 *         
 *             [%d{yyyy-MM-dd HH:mm:ss.SSS}] <%-36X{AWSRequestId:-request-id-not-set-by-lambda-runtime}> %-5level %logger{10} - %msg%n 
 *          
 *      
 *
 *     
 *          
 *      
 *
 *  
 * }
 */
public class AwsLambdaAppender extends UnsynchronizedAppenderBase {
    private final LambdaLogger logger = LambdaRuntime.getLogger();
    private Encoder encoder;
    public AwsLambdaAppender() {
        LambdaRuntimeInternal.setUseLog4jAppender(true);
    }
    @Override
    protected void append(ILoggingEvent event) {
        logger.log(encoder.encode(event));
    }
    public Encoder getEncoder() {
        return encoder;
    }
    public void setEncoder(Encoder encoder) {
        this.encoder = encoder;
    }
}
        © 2015 - 2025 Weber Informatics LLC | Privacy Policy