mcp-extended-tools
Version:
Extended tools for command execution
94 lines (82 loc) • 2.85 kB
JavaScript
const winston = require('winston');
require('winston-daily-rotate-file');
const path = require('path');
const fs = require('fs').promises;
class LogManager {
constructor(options = {}) {
const {
logDir = 'logs',
maxSize = '20m',
maxFiles = '14d',
level = 'info'
} = options;
this.logDir = logDir;
this.initLogger(maxSize, maxFiles, level);
}
initLogger(maxSize, maxFiles, level) {
const logFormat = winston.format.combine(
winston.format.timestamp(),
winston.format.json()
);
this.logger = winston.createLogger({
level,
format: logFormat,
defaultMeta: { service: 'mcp-extended-tools' },
transports: [
// Rotating file for errors
new winston.transports.DailyRotateFile({
filename: path.join(this.logDir, 'error-%DATE%.log'),
datePattern: 'YYYY-MM-DD',
maxSize,
maxFiles,
level: 'error'
}),
// Rotating file for all logs
new winston.transports.DailyRotateFile({
filename: path.join(this.logDir, 'combined-%DATE%.log'),
datePattern: 'YYYY-MM-DD',
maxSize,
maxFiles
})
]
});
// Add console transport in development
if (process.env.NODE_ENV !== 'production') {
this.logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
}
async cleanup(daysToKeep = 14) {
try {
const files = await fs.readdir(this.logDir);
const now = Date.now();
const maxAge = daysToKeep * 24 * 60 * 60 * 1000;
for (const file of files) {
const filePath = path.join(this.logDir, file);
const stats = await fs.stat(filePath);
if (now - stats.mtime.getTime() > maxAge) {
await fs.unlink(filePath);
}
}
} catch (error) {
this.logger.error('Error cleaning up logs', { error: error.message });
}
}
// Schedule automatic cleanup
scheduleCleanup(daysToKeep = 14, intervalDays = 1) {
setInterval(() => {
this.cleanup(daysToKeep).catch(error => {
console.error('Scheduled log cleanup failed:', error);
});
}, intervalDays * 24 * 60 * 60 * 1000);
}
}
// Create singleton instance
const logManager = new LogManager();
// Schedule daily cleanup by default
logManager.scheduleCleanup();
module.exports = {
LogManager,
logManager
};