@nowarajs/logger
Version:
Type-safe logging library for Bun with advanced TypeScript body intersection, modular strategy pattern, transform streams, and immutable API design.
45 lines (43 loc) • 1.41 kB
JavaScript
// @bun
// source/strategies/consoleLogger.ts
class ConsoleLoggerStrategy {
_colorize;
constructor(colorize = false) {
this._colorize = colorize;
}
log(level, date, object) {
const colors = {
ERROR: "\x1B[31m",
WARN: "\x1B[33m",
INFO: "\x1B[36m",
DEBUG: "\x1B[34m",
LOG: "\x1B[35m"
};
const dateColor = this._colorize ? "\x1B[33m" : "";
const colorReset = this._colorize ? "\x1B[0m" : "";
const logLevelColor = this._colorize ? colors[level] : "";
const sanitizedObject = typeof object === "string" ? object : JSON.stringify(object);
const prefixDate = `[${dateColor}${date.toISOString().replace(/T/, " ").replace(/\..+/, "")}${colorReset}]`;
const message = `${prefixDate} ${logLevelColor}${level}${colorReset} : ${sanitizedObject}`;
console[level.toLowerCase()](message);
}
}
// source/strategies/fileLogger.ts
import { appendFile } from "fs/promises";
class FileLoggerStrategy {
_path;
constructor(path) {
this._path = path;
}
async log(level, date, object) {
const prefixDate = `[${date.toISOString().replace(/T/, " ").replace(/\..+/, "")}]`;
const sanitizedObject = typeof object === "string" ? object : JSON.stringify(object);
const message = `${prefixDate} ${level} : ${sanitizedObject}`;
await appendFile(this._path, `${message}
`);
}
}
export {
FileLoggerStrategy,
ConsoleLoggerStrategy
};