Applicable when
- You want to enable or disable logging for your lambda based on the configuration (e.g. environment variable)
Non-applicable when
- None
Implementation
A simple drop-in replacement for the Typescript console logger (created as a separate file and then imported):
// tslint:disable:no-any // tslint:disable:no-console /** * Set lambda env variable LOG_LEVEL to one of the values below */ enum LogLevel { DEBUG = 'DEBUG', INFO = 'INFO', WARN = 'WARN', ERROR = 'ERROR', } const DefaultLogLevel = LogLevel.DEBUG; const LogLevelPriority = { [LogLevel.DEBUG]: 0, [LogLevel.INFO]: 1, [LogLevel.WARN]: 2, [LogLevel.ERROR]: 3, }; export class Log { public static debug(message?: any, ...optionalParams: any[]): void { if (Log.isLogEnabled(LogLevel.DEBUG)) { console.debug(message, optionalParams); } } public static info(message?: any, ...optionalParams: any[]): void { if (Log.isLogEnabled(LogLevel.INFO)) { console.info(message, optionalParams); } } public static warn(message?: any, ...optionalParams: any[]): void { if (Log.isLogEnabled(LogLevel.WARN)) { console.warn(message, optionalParams); } } public static error(message?: any, ...optionalParams: any[]): void { if (Log.isLogEnabled(LogLevel.ERROR)) { console.error(message, optionalParams); } } private static currentLogLevel(): LogLevel { return (process.env.LOG_LEVEL as LogLevel) ?? DefaultLogLevel; } private static isLogEnabled(level: LogLevel): boolean { return LogLevelPriority[Log.currentLogLevel()] <= LogLevelPriority[level]; } }
If you need to log to another destination, you can easily add it to this logger.
Usage:
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda'; import { Log } from '../util/logging'; // Proxy integration handler should conform this type: Handler<APIGatewayProxyEvent, APIGatewayProxyResult> export async function handler(event: APIGatewayProxyEvent): Promise { Log.info(`Method called for api ${event.requestContext.apiId}`); if (event.body) { try { Log.debug('Payload before parsing', event.body); const payload = JSON.parse(event.body); Log.info('Method invoked with payload', payload); } catch (e) { Log.warn('Cannot process payload', event.body, e); } } return { statusCode: 200, body: JSON.stringify({ message: 'OK', }), }; }
Comments
0 comments
Please sign in to leave a comment.