90 lines
2.4 KiB
TypeScript
90 lines
2.4 KiB
TypeScript
import winston from 'winston';
|
||
import 'winston-daily-rotate-file';
|
||
import path from 'path';
|
||
|
||
// Define log levels
|
||
const levels = {
|
||
error: 0,
|
||
warn: 1,
|
||
info: 2,
|
||
http: 3,
|
||
debug: 4,
|
||
};
|
||
|
||
// Define log level based on environment
|
||
const level = () => {
|
||
const env = process.env.NODE_ENV || 'development';
|
||
return env === 'development' ? 'debug' : 'warn';
|
||
};
|
||
|
||
// Define colors for each level
|
||
const colors = {
|
||
error: 'red',
|
||
warn: 'yellow',
|
||
info: 'green',
|
||
http: 'magenta',
|
||
debug: 'blue',
|
||
};
|
||
|
||
// Add colors to winston
|
||
winston.addColors(colors);
|
||
|
||
// Custom format for logging
|
||
const logSimpleFormat = winston.format.combine(
|
||
winston.format.timestamp({ format: 'DD-MM-YYYY HH:mm:ss:ms' }),
|
||
winston.format.printf(
|
||
({ timestamp, level, message }) => `${timestamp} [${level}] ${message}`
|
||
)
|
||
);
|
||
|
||
// Custom format for logging
|
||
const logFormat = winston.format.combine(
|
||
winston.format.timestamp({ format: 'DD-MM-YYYY HH:mm:ss:ms' }),
|
||
winston.format.printf((info) => {
|
||
const maxLevelLength = 5; // "error" — самый длинный уровень
|
||
const paddedLevel = info.level.padEnd(maxLevelLength, ' '); // Выровнять уровень
|
||
return `[${info.timestamp}] ${paddedLevel} : ${info.message}`;
|
||
})
|
||
);
|
||
|
||
// File transport options with uncolored plain text format
|
||
const fileRotateTransport = new winston.transports.DailyRotateFile({
|
||
filename: path.join('logs', '%DATE%-server.log'),
|
||
datePattern: 'DD-MM-YYYY',
|
||
zippedArchive: true,
|
||
maxSize: '20m',
|
||
maxFiles: '14d',
|
||
level: 'info', // Устанавливаем уровень логирования для файла
|
||
format: winston.format.combine(
|
||
winston.format.uncolorize(), // Убираем цвета для файлового формата
|
||
logFormat // Используем текстовый формат без JSON
|
||
),
|
||
});
|
||
|
||
// Create the logger
|
||
const logger = winston.createLogger({
|
||
level: level(),
|
||
levels,
|
||
transports: [
|
||
// Логи в файл
|
||
fileRotateTransport,
|
||
|
||
// Логи в консоль с цветами
|
||
new winston.transports.Console({
|
||
format: winston.format.combine(
|
||
winston.format.colorize({ all: true }),
|
||
logFormat
|
||
),
|
||
}),
|
||
],
|
||
});
|
||
|
||
// Create a stream object for Morgan middleware
|
||
const stream = {
|
||
write: (message: string) => {
|
||
logger.http(message.trim());
|
||
},
|
||
};
|
||
|
||
export { logger, stream };
|