87 lines
2.6 KiB
JavaScript
87 lines
2.6 KiB
JavaScript
import winston from 'winston';
|
|
import 'winston-daily-rotate-file';
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
import { fileURLToPath } from 'url';
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = path.dirname(__filename);
|
|
const rootDir = path.dirname(__dirname);
|
|
|
|
// Create Winston logger
|
|
export const createLogger = (clientConfig) => {
|
|
const { logging } = clientConfig;
|
|
const transports = [];
|
|
|
|
// Console transport
|
|
if (logging.console.enabled) {
|
|
transports.push(new winston.transports.Console({
|
|
level: logging.console.level,
|
|
format: winston.format.combine(
|
|
winston.format.timestamp({
|
|
format: logging.file.timestampFormat
|
|
}),
|
|
logging.console.colorize ? winston.format.colorize() : winston.format.uncolorize(),
|
|
winston.format.printf(info => `[${info.timestamp}] [${clientConfig.id}] [${info.level}] ${info.message}`)
|
|
)
|
|
}));
|
|
}
|
|
|
|
// Combined file transport with rotation
|
|
if (logging.file.combined.enabled) {
|
|
const logDir = path.join(rootDir, logging.file.combined.location);
|
|
|
|
// Create log directory if it doesn't exist
|
|
if (!fs.existsSync(logDir)) {
|
|
fs.mkdirSync(logDir, { recursive: true });
|
|
}
|
|
|
|
const combinedTransport = new winston.transports.DailyRotateFile({
|
|
filename: path.join(logDir, `${clientConfig.id}-combined-%DATE%.log`),
|
|
datePattern: logging.file.dateFormat,
|
|
level: logging.file.combined.level,
|
|
maxSize: logging.file.combined.maxSize,
|
|
maxFiles: logging.file.combined.maxFiles,
|
|
format: winston.format.combine(
|
|
winston.format.timestamp({
|
|
format: logging.file.timestampFormat
|
|
}),
|
|
winston.format.printf(info => `[${info.timestamp}] [${info.level}] ${info.message}`)
|
|
)
|
|
});
|
|
|
|
transports.push(combinedTransport);
|
|
}
|
|
|
|
// Error file transport with rotation
|
|
if (logging.file.error.enabled) {
|
|
const logDir = path.join(rootDir, logging.file.error.location);
|
|
|
|
// Create log directory if it doesn't exist
|
|
if (!fs.existsSync(logDir)) {
|
|
fs.mkdirSync(logDir, { recursive: true });
|
|
}
|
|
|
|
const errorTransport = new winston.transports.DailyRotateFile({
|
|
filename: path.join(logDir, `${clientConfig.id}-error-%DATE%.log`),
|
|
datePattern: logging.file.dateFormat,
|
|
level: logging.file.error.level,
|
|
maxSize: logging.file.error.maxSize,
|
|
maxFiles: logging.file.error.maxFiles,
|
|
format: winston.format.combine(
|
|
winston.format.timestamp({
|
|
format: logging.file.timestampFormat
|
|
}),
|
|
winston.format.printf(info => `[${info.timestamp}] [${info.level}] ${info.message}`)
|
|
)
|
|
});
|
|
|
|
transports.push(errorTransport);
|
|
}
|
|
|
|
return winston.createLogger({
|
|
levels: winston.config.npm.levels,
|
|
transports
|
|
});
|
|
};
|