Skip to content

Logger

This file defines the Logger class, a simple and extendable logging utility for the @sodacore/core library. It wraps standard console logging methods, providing consistent formatting, colorization, and support for log listeners.


Features

  • Consistent Logging: Formats log messages with timestamps, namespaces, and tags.
  • Colorized Output: Uses chalk to color log levels and tags for better readability.
  • Listener Support: Allows external listeners to subscribe to log events for custom handling.
  • Log Levels: Supports info, warn, error, and custom log types.

Usage

typescript
import Logger from './provider/logger';

const logger = new Logger();

logger.info('This is an info message');
logger.warn('This is a warning');
logger.error('This is an error');

// Add a custom listener
const listenerId = Symbol('my-listener');
logger.addListener(listenerId, (log) => {
	console.log('Received log:', log);
});

API

Methods

addListener(unique: symbol, callback: (item: ILogMessage) => void): void

Adds a listener that will be called whenever a log message is emitted.

removeListener(unique: symbol): void

Removes a previously added listener.

getListenerCount(): number

Returns the number of currently registered listeners.

async info(message: string): Promise<void>

Logs an info-level message.

async warn(message: string): Promise<void>

Logs a warning-level message.

async error(message: string): Promise<void>

Logs an error-level message.


Private Methods

private format(type: ILoggerType, message: string): string

Formats the log message with timestamp, log type, namespace, and tags, applying colorization.

private getNamespace(message: string): string | undefined

Extracts and formats the namespace from the message (e.g., [APP]).

private getColour(type: string): chalk.Chalk

Returns the appropriate chalk color function for the log type.

private matchTags(message: string): string

Finds and colorizes tags in the message (e.g., {tag} becomes #tag).


Notes

  • Log messages can include namespaces (e.g., [APP]: ...) and tags (e.g., {tag}) for enhanced formatting.
  • Listeners receive an object with the formatted message, original message, and log type.
  • The logger is designed to be extendable and can be integrated with other logging systems or transports.

Released under the Apache-2.0 License.