@rollercoaster-dev/rd-logger
Version:
A neurodivergent-friendly logger for Rollercoaster.dev projects
60 lines (59 loc) • 2.83 kB
JavaScript
import chalk from 'chalk';
import { DEFAULT_LEVEL_COLORS, DEFAULT_LEVEL_ICONS, } from '../logger.config';
import { formatDate, safeStringify } from '../utils';
/**
* Console transport for the logger
*/
export class ConsoleTransport {
constructor(options = {}) {
var _a, _b, _c;
this.name = 'console';
this.prettyPrint = (_a = options.prettyPrint) !== null && _a !== void 0 ? _a : true;
this.colorize = (_b = options.colorize) !== null && _b !== void 0 ? _b : true;
this.use24HourFormat = (_c = options.use24HourFormat) !== null && _c !== void 0 ? _c : true;
this.levelColors = Object.assign(Object.assign({}, DEFAULT_LEVEL_COLORS), (options.levelColors || {}));
this.levelIcons = Object.assign(Object.assign({}, DEFAULT_LEVEL_ICONS), (options.levelIcons || {}));
}
/**
* Log a message to the console
*/
log(level, message, timestamp, context) {
const logLevel = level;
const icon = this.levelIcons[logLevel];
// Format timestamp
const now = new Date(timestamp);
const readableTimestamp = formatDate(now, this.use24HourFormat);
const displayTimestamp = this.prettyPrint ? readableTimestamp : timestamp;
const colorizedTimestamp = this.colorize
? chalk.gray(displayTimestamp)
: displayTimestamp;
// Format level and message
const colorizedLevel = this.colorize
? this.levelColors[logLevel](level.toUpperCase())
: level.toUpperCase();
const colorizedMessage = this.colorize
? chalk.whiteBright(message)
: message;
// Construct console output
let consoleOutput = `\n${icon} ${colorizedLevel} ${colorizedTimestamp}\n ➤ ${colorizedMessage}`;
// Add context if available
if (Object.keys(context).length) {
for (const [key, value] of Object.entries(context)) {
const formattedValue = typeof value === 'object' && value !== null
? safeStringify(value)
: String(value);
const colorizedKey = this.colorize ? chalk.gray(key) : key;
const colorizedValue = this.colorize
? chalk.cyan(formattedValue)
: formattedValue;
consoleOutput += `\n • ${colorizedKey}: ${colorizedValue}`;
}
}
const divider = this.colorize
? chalk.dim('\n────────────────────────────────────')
: '\n────────────────────────────────────';
consoleOutput += divider;
// Output to console
console.log(consoleOutput);
}
}