@tryloop/oats
Version:
🌾 OATS - OpenAPI TypeScript Sync. The missing link between your OpenAPI specs and TypeScript applications. Automatically watch, generate, and sync TypeScript clients from your API definitions.
103 lines • 3.49 kB
JavaScript
import chalk from 'chalk';
import { appendFileSync, mkdirSync } from 'fs';
import { dirname } from 'path';
export var LogLevel;
(function (LogLevel) {
LogLevel["DEBUG"] = "debug";
LogLevel["INFO"] = "info";
LogLevel["WARN"] = "warn";
LogLevel["ERROR"] = "error";
})(LogLevel || (LogLevel = {}));
export class Logger {
context;
static logLevel = LogLevel.INFO;
static logFile;
static showTimestamps = false;
static useColors = true;
constructor(context) {
this.context = context;
}
static setLogLevel(level) {
Logger.logLevel = level;
}
static setShowTimestamps(show) {
Logger.showTimestamps = show;
}
static setUseColors(use) {
Logger.useColors = use;
}
static setLogFile(filePath) {
if (filePath) {
Logger.logFile = filePath;
// Ensure directory exists
try {
mkdirSync(dirname(filePath), { recursive: true });
}
catch (error) {
// Ignore if directory already exists
}
}
}
shouldLog(level) {
const levels = [
LogLevel.DEBUG,
LogLevel.INFO,
LogLevel.WARN,
LogLevel.ERROR,
];
const currentIndex = levels.indexOf(Logger.logLevel);
const targetIndex = levels.indexOf(level);
return targetIndex >= currentIndex;
}
formatMessage(level, message) {
let formatted = '';
if (Logger.showTimestamps) {
const timestamp = new Date().toISOString();
formatted += `[${timestamp}] `;
}
formatted += `[${level.toUpperCase()}] [${this.context}] ${message}`;
return formatted;
}
logToFile(level, message, ...args) {
// Only log to file if file path is set and log level is debug
if (Logger.logFile && Logger.logLevel === LogLevel.DEBUG) {
try {
const logEntry = `${this.formatMessage(level, message)} ${args
.map((arg) => typeof arg === 'object' ? JSON.stringify(arg) : String(arg))
.join(' ')}\n`;
appendFileSync(Logger.logFile, logEntry);
}
catch (error) {
// Silently fail if file logging fails
}
}
}
colorize(text, color) {
return Logger.useColors ? color(text) : text;
}
debug(message, ...args) {
if (this.shouldLog(LogLevel.DEBUG)) {
console.log(this.colorize(this.formatMessage(LogLevel.DEBUG, message), chalk.gray), ...args);
}
this.logToFile(LogLevel.DEBUG, message, ...args);
}
info(message, ...args) {
if (this.shouldLog(LogLevel.INFO)) {
console.log(this.colorize(this.formatMessage(LogLevel.INFO, message), chalk.blue), ...args);
}
this.logToFile(LogLevel.INFO, message, ...args);
}
warn(message, ...args) {
if (this.shouldLog(LogLevel.WARN)) {
console.warn(this.colorize(this.formatMessage(LogLevel.WARN, message), chalk.yellow), ...args);
}
this.logToFile(LogLevel.WARN, message, ...args);
}
error(message, ...args) {
if (this.shouldLog(LogLevel.ERROR)) {
console.error(this.colorize(this.formatMessage(LogLevel.ERROR, message), chalk.red), ...args);
}
this.logToFile(LogLevel.ERROR, message, ...args);
}
}
//# sourceMappingURL=logger.js.map