Build a comprehensive logging system with different log levels, structured logging, and log aggregation
Create a logging system that captures application events, errors, and metrics with different severity levels, structured formatting, and log aggregation capabilities.
const fs = require('fs');
const path = require('path');
class Logger {
constructor(level = 'info') {
this.levels = { debug: 0, info: 1, warn: 2, error: 3 };
this.currentLevel = this.levels[level];
}
log(level, message, metadata = {}) {
if (this.levels[level] >= this.currentLevel) {
const logEntry = {
timestamp: new Date().toISOString(),
level,
message,
...metadata
};
console.log(JSON.stringify(logEntry));
this.writeToFile(logEntry);
}
}
writeToFile(entry) {
const logFile = path.join(__dirname, 'logs', 'app.log');
fs.appendFileSync(logFile, JSON.stringify(entry) + '\n');
}
}