import winston from 'winston'; import path from 'path'; import { fileURLToPath } from 'url'; import { config } from '../config/index.js'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const logsDir = path.join(__dirname, '../../logs'); const logFormat = winston.format.combine( winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), winston.format.errors({ stack: true }), winston.format.printf(({ timestamp, level, message, stack }) => { return `${timestamp} [${level.toUpperCase()}]: ${message}${stack ? '\n' + stack : ''}`; }) ); const transports: winston.transport[] = [ new winston.transports.Console({ format: winston.format.combine( winston.format.colorize(), logFormat ), }), ]; // 生产环境添加文件日志 if (config.env === 'production') { transports.push( new winston.transports.File({ filename: path.join(logsDir, 'error.log'), level: 'error', format: logFormat, }), new winston.transports.File({ filename: path.join(logsDir, 'combined.log'), format: logFormat, }) ); } export const logger = winston.createLogger({ level: config.env === 'production' ? 'info' : 'debug', transports, });