UNPKG

@analog-tools/logger

Version:

Logging utility for AnalogJS applications

250 lines (249 loc) 9.59 kB
import { LoggerConfig, LogLevelEnum, LogStyling, LogContext } from './logger.types'; import { ErrorParam } from './error-serialization'; import { LoggerStyleEngine } from './logger-style-engine'; /** * Logger service implementation using standard console * Can be injected using the @analog-tools/inject package * Serves as both the main logger and child logger with context * Uses LoggerStyleEngine for all formatting and styling operations */ export declare class LoggerService { private config; /** * Mark this service as injectable * This is required for the @analog-tools/inject package to recognize it */ static INJECTABLE: boolean; private logLevel; private name; private childLoggers; private disabledContexts; private activeGroups; private context?; private parentLogger?; private styleEngine; private deduplicator?; /** * Create a new LoggerService * @param config The logger configuration * @param styleEngine Optional style engine (will be created if not provided) * @param context Optional context for child logger * @param parent Optional parent logger for child logger */ constructor(config?: LoggerConfig, styleEngine?: LoggerStyleEngine, context?: string, parent?: LoggerService); /** * Check if this logger's context is enabled * Always returns true for root logger */ isContextEnabled(): boolean; /** * Set disabled contexts for this logger * @param contexts Array of context names to disable */ setDisabledContexts(contexts: string[]): void; /** * Get the current log level * @returns The current log level */ getLogLevel(): LogLevelEnum; /** * Get disabled contexts * @returns Array of disabled context names */ getDisabledContexts(): string[]; /** * Enable or disable colored output * @param enabled Whether colors should be enabled */ setUseColors(enabled: boolean): void; /** * Check if colors are enabled * @returns Whether colors are enabled */ getUseColors(): boolean; /** * Create a child logger with a specific context * @param context The context for the child logger * @returns A new logger instance with the given context */ forContext(context: string): LoggerService; /** * Start a new log group with the given name * All subsequent log messages will be indented * @param groupName The name of the group */ group(groupName: string): void; /** * End a log group with the given name * Subsequent log messages will no longer be indented * @param groupName The name of the group (optional, will end the most recent group if not provided) */ groupEnd(groupName?: string): void; /** * Log a trace message * @param message The message to log * @param data Additional data to log * @param metadata Optional metadata for styling and icons */ trace(message: string, ...data: unknown[]): void; trace(message: string, metadata: LogStyling, ...data: unknown[]): void; /** * Log a debug message * @param message The message to log * @param data Additional data to log * @param metadata Optional metadata for styling and icons */ debug(message: string, ...data: unknown[]): void; debug(message: string, metadata: LogStyling, ...data: unknown[]): void; /** * Log an info message * @param message The message to log * @param data Additional data to log * @param metadata Optional metadata for styling and icons */ info(message: string, ...data: unknown[]): void; info(message: string, metadata: LogStyling, ...data: unknown[]): void; /** * Log a warning message * @param message The message to log * @param data Additional data to log * @param metadata Optional metadata for styling and icons */ warn(message: string, ...data: unknown[]): void; warn(message: string, metadata: LogStyling, ...data: unknown[]): void; /** * Log an error message with enhanced error handling and type safety * * Supports multiple overloads for flexibility: * - error(message: string): Simple error message * - error(error: Error): Log an Error object * - error(message: string, error: Error): Message with Error object * - error(message: string, context: LogContext): Message with structured context * - error(message: string, error: Error, context: LogContext): Message with Error and context * - error(message: string, error?: ErrorParam, ...data: unknown[]): Backwards compatible overload * - error(message: string, ...data: unknown[], styling: LogStyling): With styling metadata * * @example * ```typescript * // Simple message * logger.error('Something went wrong'); * * // With Error object * logger.error('Database connection failed', dbError); * * // With context * logger.error('User validation failed', { userId: '123', action: 'login' }); * * // With Error and context * logger.error('Payment processing failed', paymentError, { orderId: 'order-123' }); * * // With styling * logger.error('Critical error', { style: 'error', icon: '❌' }); * ``` */ error(message: string): void; error(error: Error): void; error(message: string, error: Error): void; error(message: string, context: LogContext): void; error(message: string, error: Error, context: LogContext): void; error(message: string, error?: ErrorParam, ...data: unknown[]): void; /** * Log a fatal error message with enhanced error handling and type safety * * Supports multiple overloads for flexibility: * - fatal(message: string): Simple fatal message * - fatal(error: Error): Log a fatal Error object * - fatal(message: string, error: Error): Message with Error object * - fatal(message: string, context: LogContext): Message with structured context * - fatal(message: string, error: Error, context: LogContext): Message with Error and context * - fatal(message: string, error?: ErrorParam, ...data: unknown[]): Backwards compatible overload * - fatal(message: string, ...data: unknown[], styling: LogStyling): With styling metadata * * @example * ```typescript * // Simple fatal message * logger.fatal('Application crashed'); * * // With Error object * logger.fatal('Critical system failure', systemError); * * // With context * logger.fatal('Out of memory', { heapUsed: '2GB', maxHeap: '1.5GB' }); * * // With Error and context * logger.fatal('Database corruption detected', dbError, { tableName: 'users' }); * * // With styling * logger.fatal('Critical error', { style: 'error', icon: '💀' }); * ``` */ fatal(message: string): void; fatal(error: Error): void; fatal(message: string, error: Error): void; fatal(message: string, context: LogContext): void; fatal(message: string, error: Error, context: LogContext): void; fatal(message: string, error?: ErrorParam, ...data: unknown[]): void; /** * Parse and normalize error method parameters to support multiple overloads * * Handles various parameter combinations: * - error(Error) -> extracts message and serializes error * - error(message) -> uses message as-is * - error(message, Error) -> uses message and serializes error * - error(message, LogContext) -> uses message and context * - error(message, Error, LogContext) -> uses all three with proper typing * - error(message, ...data) -> backwards compatibility mode * * @private * @param messageOrError - String message or Error object * @param errorOrContext - Error object, LogContext, or additional data * @param contextOrData - LogContext or additional data * @param additionalData - Extra data for backwards compatibility * @returns Parsed parameters with normalized structure */ private parseErrorParameters; /** * Type guard to check if an object is LogMetadata * * LogMetadata is defined as a plain object that is not: * - null or undefined * - An Array * - An Error instance * - A Date instance * - A RegExp instance * - A Function * * @private * @param obj - Object to check * @returns True if object matches LogMetadata interface */ private isLogContext; /** * Cast a string to a LogLevel, with runtime validation and warning for invalid levels * @param level String representation of log level * @returns Numeric LogLevel * @private */ private castLoglevel; /** * Safely format a message using the style engine * Catches and logs any errors from the style engine * @param args Arguments for the style engine formatMessage method * @returns The formatted message * @private */ private safeFormatMessage; /** * Handle deduplication for a log message * @param level Log level * @param message Message text * @returns True if message should be logged immediately, false if batched * @private */ private shouldLogImmediately; /** * Deduplication handler for all log methods * Returns true if the message should be logged immediately, false if batched */ private handleDeduplication; }