@rollercoaster-dev/rd-logger
Version:
A neurodivergent-friendly logger for Rollercoaster.dev projects
67 lines • 2.81 kB
JavaScript
import chalk from "chalk";
import { DEFAULT_LEVEL_COLORS, DEFAULT_LEVEL_ICONS } from "../logger.config.js";
import { formatDate, safeStringify } from "../utils.js";
/**
* Console transport for the logger
*/
export class ConsoleTransport {
name = "console";
prettyPrint;
colorize;
use24HourFormat;
levelColors;
levelIcons;
constructor(options = {}) {
this.prettyPrint = options.prettyPrint ?? true;
this.colorize = options.colorize ?? true;
this.use24HourFormat = options.use24HourFormat ?? true;
this.levelColors = {
...DEFAULT_LEVEL_COLORS,
...(options.levelColors || {}),
};
this.levelIcons = { ...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);
}
}
//# sourceMappingURL=console.transport.js.map