logger.ts•1.3 kB
import { RequestLog } from "./types";
export class Logger {
private static logs: RequestLog[] = [];
private static maxLogs = 1000;
static log(level: string, message: string, meta?: any) {
const timestamp = new Date().toISOString();
const logEntry = {
timestamp,
level,
message,
...(meta && { meta }),
};
console.log(JSON.stringify(logEntry));
}
static info(message: string, meta?: any) {
this.log("info", message, meta);
}
static error(message: string, meta?: any) {
this.log("error", message, meta);
}
static warn(message: string, meta?: any) {
this.log("warn", message, meta);
}
static debug(message: string, meta?: any) {
if (process.env.NODE_ENV === "development") {
this.log("debug", message, meta);
}
}
static logRequest(log: RequestLog) {
// Check if request logging is enabled
if (process.env.LOG_REQUESTS === "false") {
return;
}
this.logs.push(log);
// Keep only the last maxLogs entries
if (this.logs.length > this.maxLogs) {
this.logs.shift();
}
this.info("HTTP Request", log);
}
static getRecentLogs(limit: number = 100): RequestLog[] {
return this.logs.slice(-limit);
}
static clearLogs() {
this.logs = [];
}
}