94 lines
2.6 KiB
TypeScript
94 lines
2.6 KiB
TypeScript
import winston from "winston";
|
|
import chalk from "chalk";
|
|
import path from "path";
|
|
import fs from "fs";
|
|
|
|
const logFileDirectory = process.env.LOG_DIR || path.join(__dirname, "..", "logs");
|
|
if (!fs.existsSync(logFileDirectory)) {
|
|
fs.mkdirSync(logFileDirectory);
|
|
}
|
|
|
|
const deleteLogFile =(filePath: string) => {
|
|
try {
|
|
fs.unlinkSync(filePath);
|
|
logger.info("Deleted expired log file", { filename: __filename });
|
|
} catch (error) {
|
|
logger.error("Failed to expired log file:", error);
|
|
}
|
|
}
|
|
|
|
const cleanExpiredLogFiles = () => {
|
|
const files = fs.readdirSync(logFileDirectory);
|
|
const now = Date.now();
|
|
const maxAgeMs = 7 * 24 * 60 * 60 * 1000;
|
|
|
|
for (const file of files) {
|
|
const filePath = path.join(logFileDirectory, file);
|
|
const stats = fs.statSync(filePath);
|
|
|
|
if (stats.isFile() && now - stats.mtimeMs > maxAgeMs) {
|
|
deleteLogFile(filePath);
|
|
}
|
|
}
|
|
};
|
|
|
|
const { combine, timestamp, errors, printf } = winston.format;
|
|
const timestampFormat = "YYYY-MM-DD HH:mm:ss";
|
|
const levelColours: Record<string, any> = {
|
|
info: chalk.green,
|
|
warn: chalk.yellow,
|
|
error: chalk.red,
|
|
debug: chalk.magenta,
|
|
}
|
|
|
|
const consoleFormat = combine(
|
|
errors({ stack: true }),
|
|
timestamp({ format: timestampFormat }),
|
|
printf(({ timestamp, level, message, filename }) => {
|
|
const levelColour = levelColours[level] || chalk.white;
|
|
|
|
level = levelColour(level);
|
|
timestamp = chalk.cyan(timestamp);
|
|
message = chalk.white(message);
|
|
filename = chalk.white(filename || "unknown")
|
|
|
|
return `[${level}] (${filename}) ${timestamp}: ${message}`;
|
|
})
|
|
);
|
|
|
|
const fileFormat = combine(
|
|
errors({ stack: true }),
|
|
timestamp({ format: timestampFormat }),
|
|
printf(({ timestamp, level, message, filename }) => {
|
|
return `[${level}] (${filename || "unknown"}) ${timestamp}: ${message}`;
|
|
})
|
|
);
|
|
|
|
const sessionTimestamp = new Date().toISOString()
|
|
.replace(/T/, "_")
|
|
.replace(/:/g, "-")
|
|
.replace(/\..+/, "");
|
|
const sessionLogFile = path.join(logFileDirectory, `${sessionTimestamp}.log`);
|
|
|
|
export const logger = winston.createLogger({
|
|
level: process.env.LOG_LEVEL || "info",
|
|
levels: winston.config.syslog.levels,
|
|
transports: [
|
|
new winston.transports.Console({
|
|
level: "debug",
|
|
format: consoleFormat
|
|
}),
|
|
new winston.transports.File({
|
|
filename: sessionLogFile,
|
|
level: "info",
|
|
format: fileFormat
|
|
})
|
|
]
|
|
});
|
|
|
|
cleanExpiredLogFiles();
|
|
|
|
export const getLogger = (file: string) => {
|
|
return logger.child({ filename: path.basename(file) });
|
|
}
|