All files / logger console-logger.ts

100% Statements 7/7
100% Branches 1/1
100% Functions 2/2
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 5218x     18x                                                       18x                   30x 30x       12x   12x      
import { BaseLogger } from './base-logger.ts';
import type { LogLevel } from './definition.ts';
import type { EmitterFormat } from './emitter.ts';
import { emitLine } from './emitter.ts';
 
/**
 * A logger that emits log messages to standard output (console.log). By default the lines are emitted with colors.
 *
 * @example
 *
 * ```ts
 * // Create a console logger
 * const logger = new ConsoleLogger();
 *
 * // Log messages at different levels
 * logger.d`Detailed debugging information`;
 *
 * // Using template literals with embedded values
 * const userId = 'user123';
 * logger.i`User ${userId} logged in successfully`;
 *
 * // Including additional context with args()
 * const error = new Error('Connection timeout');
 * logger.args(error).e`Database operation failed: ${error}`;
 *
 * // Using with level filtering - only errors and above
 * const productionLogger = new ConsoleLogger('error');
 * productionLogger.i`This won't be logged`;
 * productionLogger.e`This will be logged to stderr`;
 * ```
 */
export class ConsoleLogger extends BaseLogger {
  private readonly format: EmitterFormat;
 
  /**
   * Creates a new ConsoleLogger instance.
   *
   * @param level - The log level to use (default: 'info')
   * @param format - The format of the emitted lines (default: 'colorful')
   */
  public constructor(level?: LogLevel, format: EmitterFormat = 'colorful') {
    super(level);
    this.format = format;
  }
 
  protected override emitLine(level: LogLevel, message: string, args: readonly unknown[]): void {
    const line = emitLine(level, message, undefined, this.format);
    // eslint-disable-next-line no-undef, no-console
    console.log(line, ...args);
  }
}