|
| 1 | +/* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. */ |
| 2 | + |
| 3 | +package com.amazonaws.services.lambda.runtime.api.client.logging; |
| 4 | + |
| 5 | +import static java.nio.charset.StandardCharsets.UTF_8; |
| 6 | + |
| 7 | +import com.amazonaws.services.lambda.runtime.api.client.api.LambdaContext; |
| 8 | +import com.amazonaws.services.lambda.runtime.LambdaLogger; |
| 9 | +import com.amazonaws.services.lambda.runtime.logging.LogFormat; |
| 10 | +import com.amazonaws.services.lambda.runtime.logging.LogLevel; |
| 11 | + |
| 12 | +/** |
| 13 | + * Provides default implementation of the convenience logger functions. |
| 14 | + * When extending AbstractLambdaLogger, only one function has to be overridden: |
| 15 | + * void logMessage(byte[] message, LogLevel logLevel); |
| 16 | + */ |
| 17 | +public abstract class AbstractLambdaLogger implements LambdaLogger { |
| 18 | + private final LogFiltering logFiltering; |
| 19 | + private final LogFormatter logFormatter; |
| 20 | + protected final LogFormat logFormat; |
| 21 | + |
| 22 | + public AbstractLambdaLogger(LogLevel logLevel, LogFormat logFormat) { |
| 23 | + this.logFiltering = new LogFiltering(logLevel); |
| 24 | + |
| 25 | + this.logFormat = logFormat; |
| 26 | + if (logFormat == LogFormat.JSON) { |
| 27 | + logFormatter = new JsonLogFormatter(); |
| 28 | + } else { |
| 29 | + logFormatter = new TextLogFormatter(); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + protected abstract void logMessage(byte[] message, LogLevel logLevel); |
| 34 | + |
| 35 | + protected void logMessage(String message, LogLevel logLevel) { |
| 36 | + logMessage(message.getBytes(UTF_8), logLevel); |
| 37 | + } |
| 38 | + |
| 39 | + @Override |
| 40 | + public void log(String message, LogLevel logLevel) { |
| 41 | + if (logFiltering.isEnabled(logLevel)) { |
| 42 | + this.logMessage(logFormatter.format(message, logLevel), logLevel); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + @Override |
| 47 | + public void log(byte[] message, LogLevel logLevel) { |
| 48 | + if (logFiltering.isEnabled(logLevel)) { |
| 49 | + // there is no formatting for byte[] messages |
| 50 | + this.logMessage(message, logLevel); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + @Override |
| 55 | + public void log(String message) { |
| 56 | + this.log(message, LogLevel.UNDEFINED); |
| 57 | + } |
| 58 | + |
| 59 | + @Override |
| 60 | + public void log(byte[] message) { |
| 61 | + this.log(message, LogLevel.UNDEFINED); |
| 62 | + } |
| 63 | + |
| 64 | + public void setLambdaContext(LambdaContext lambdaContext) { |
| 65 | + this.logFormatter.setLambdaContext(lambdaContext); |
| 66 | + } |
| 67 | +} |
0 commit comments