logaro
Version:
Structured logging middleware for Express. Tracks request timing, IP, status, method, and endpoint. Supports colorized console and JSON log files.
57 lines (56 loc) • 2.37 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const winston_1 = require("winston");
const path_1 = __importDefault(require("path"));
const { combine, timestamp, printf, colorize, json } = winston_1.format;
const shouldSaveToFile = process.env.LOGARO_SAVE_LOGS === "true";
const logFolder = "Logaro";
const logLevel = process.env.LOG_LEVEL || "info";
const consoleFormat = printf(({ level, message, timestamp, ...metadata }) => {
let logOutput = `${timestamp} ${level}: ${message}`;
if (metadata.method && metadata.status) {
const method = metadata.method;
const status = metadata.status;
const duration = metadata.durationMs ? `${metadata.durationMs}ms` : "";
const url = metadata.endpoint || "";
logOutput = `${timestamp} ${level}: \x1b[36m${method}\x1b[0m \x1b[33m${url}\x1b[0m \x1b[35m${status}\x1b[0m \x1b[32m${duration}\x1b[0m - ${message}`;
}
if (metadata.errorStack) {
logOutput += `\n\x1b[31m${metadata.errorStack}\x1b[0m`;
}
else if (Object.keys(metadata).length > 0 && !metadata.method) {
logOutput += ` \n${JSON.stringify(metadata, null, 2)}`;
}
return logOutput;
});
const logTransports = [
new winston_1.transports.Console({
level: logLevel,
format: combine(colorize({ all: true }), timestamp({ format: "HH:mm:ss" }), consoleFormat),
}),
];
if (shouldSaveToFile) {
logTransports.push(new winston_1.transports.File({
filename: path_1.default.join(logFolder, "app-combined.log"),
level: "info",
format: combine(timestamp({ format: "YYYY-MM-DD HH:mm:ss" }), json()),
maxsize: 5242880,
maxFiles: 5,
}));
}
const exceptionHandlers = shouldSaveToFile
? [new winston_1.transports.File({ filename: path_1.default.join(logFolder, "exceptions.log") })]
: [];
const rejectionHandlers = shouldSaveToFile
? [new winston_1.transports.File({ filename: path_1.default.join(logFolder, "rejections.log") })]
: [];
const logger = (0, winston_1.createLogger)({
level: logLevel,
transports: logTransports,
exceptionHandlers: exceptionHandlers,
rejectionHandlers: rejectionHandlers,
});
exports.default = logger;