UNPKG

@energica-city/shared-amplify-utils

Version:

Shared utilities for AWS Amplify projects

222 lines 7.26 kB
/** * Defines the log levels for the logger. */ export declare enum LogLevel { NONE = 0, ERROR = 1, WARN = 2, INFO = 3, DEBUG = 4 } /** * Defines the structure for contextual information attached to logs. */ export interface LogContext { requestId?: string; operation?: string; userId?: string; [key: string]: unknown; } /** * Defines the structure for a structured log entry in JSON format. */ export interface StructuredLogEntry { timestamp: string; level: string; message: string; context?: LogContext; data?: unknown; awsRequestId?: string; functionName?: string; xrayTraceId?: string; environment?: string; } /** * A singleton Logger class that provides structured and text-based logging. * It supports different log levels, contextual information, and can adapt * its output format based on the environment (e.g., development, production, AWS Lambda). */ declare class Logger { private static instance; private level; private context; private useStructuredLogging; private environment; private constructor(); /** * Detects the current runtime environment. * It checks for Amplify-specific environment variables, AWS Lambda function names, * and standard `NODE_ENV`. Defaults to 'development'. * @returns The detected environment name (e.g., 'production', 'development'). */ private detectEnvironment; /** * Determines whether to use structured (JSON) logging. * Structured logging is enabled if the `STRUCTURED_LOGGING` environment variable is 'true', * or if the environment is detected as 'pro' or 'aws-lambda'. * @returns `true` if structured logging should be used, otherwise `false`. */ private shouldUseStructuredLogging; /** * Gets the singleton instance of the Logger. * @returns The singleton Logger instance. */ static getInstance(): Logger; /** * Sets the log level for the logger. Messages with a level lower than * the set level will not be logged. * @param level The log level to set. */ setLevel(level: LogLevel): void; /** * Gets the current log level of the logger. * @returns The current LogLevel. */ getLevel(): LogLevel; /** * Gets the name of the current log level. * @returns The name of the current log level (e.g., 'INFO', 'DEBUG'). */ getLevelName(): string; /** * Gets the detected runtime environment. * @returns The name of the environment (e.g., 'production', 'development'). */ getEnvironment(): string; /** * Enables or disables structured (JSON) logging. * @param enabled `true` to enable structured logging, `false` to disable it. */ setStructuredLogging(enabled: boolean): void; /** * Checks if structured logging is currently enabled. * @returns `true` if structured logging is enabled, otherwise `false`. */ isStructuredLoggingEnabled(): boolean; /** * Sets context that will be included in all subsequent log messages. * The new context is merged with any existing context. * @param newContext A partial LogContext object to merge into the current context. */ setContext(newContext: Partial<LogContext>): void; /** * Gets a copy of the current log context. * @returns A copy of the current LogContext. */ getContext(): LogContext; /** * Clears the current log context. */ clearContext(): void; /** * Retrieves AWS Lambda-specific context from environment variables. * @returns An object containing AWS request ID, function name, trace ID, and environment. */ private getAWSContext; /** * Creates a structured log entry object. * @param level The log level name (e.g., 'ERROR'). * @param message The main log message. * @param data Additional data to include in the log. * @returns A StructuredLogEntry object. */ private createStructuredLog; /** * Formats a log message with context for plain text logging. * @param level The log level name (e.g., 'INFO'). * @param args The array of arguments to log. * @returns A formatted log string. */ private formatWithContext; /** * The main logging method that handles both structured and text logging. * It checks the log level and formats the message accordingly. * @param level The log level of the message. * @param levelName The name of the log level. * @param args The arguments to log. */ private logMessage; /** * Logs an error message. * @param args The arguments to log. */ error(...args: unknown[]): void; /** * Logs a warning message. * @param args The arguments to log. */ warn(...args: unknown[]): void; /** * Logs an informational message. * @param args The arguments to log. */ info(...args: unknown[]): void; /** * Logs a debug message. * @param args The arguments to log. */ debug(...args: unknown[]): void; /** * Logs a message directly to the console without level checking or formatting. * All arguments are stringified. * @param args The arguments to log. */ log(...args: unknown[]): void; } /** * # Usage in AWS Lambda with CloudWatch * * This logger is optimized for use within AWS Lambda functions, sending structured * JSON logs to Amazon CloudWatch. * * ## Structured Logging * * When running in a detected AWS Lambda environment, the logger automatically * switches to structured JSON format. This provides several advantages in CloudWatch: * * - **Searchable Logs**: Structured logs enable easy searching and filtering in CloudWatch Logs * based on JSON fields (e.g., `level`, `context.requestId`, `data.someValue`). * - **CloudWatch Logs Insights**: Structured logs can be queried with CloudWatch * Logs Insights for powerful analysis and visualization. * - **Automatic Context**: The logger automatically captures Lambda-specific context * like `awsRequestId` and `functionName`. * * ## Example Handler * * ```typescript * import { logger } from './util/log'; * * export const handler = async (event, context) => { * // Set context for all logs in this invocation for easy tracking * logger.setContext({ * awsRequestId: context.awsRequestId, * userId: event.arguments.userId, // Example * }); * * try { * logger.info('Function started', { input: event.arguments }); * * // ... business logic implementation ... * * const result = { success: true }; * logger.info('Function finished successfully', { result }); * return result; * * } catch (error) { * // Log the error with structured data * logger.error('An unhandled error occurred', { * error: error.message, * stack: error.stack, * }); * // Rethrow or handle as appropriate * throw error; * } finally { * // Clear context to avoid leaking information between invocations * logger.clearContext(); * } * }; * ``` */ export declare const logger: Logger; export {}; //# sourceMappingURL=index.d.ts.map