Spaces:
Paused
Paused
| const winston = require('winston'); | |
| const moment = require('moment-timezone'); | |
| // 自定义时间戳格式化函数,转换为北京时间 | |
| const timestampInBeijing = winston.format((info) => { | |
| info.timestamp = moment().tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss'); | |
| return info; | |
| }); | |
| // 使用 printf 格式化日志输出 | |
| const myFormat = winston.format.printf(({ level, message, timestamp, meta }) => { | |
| //console.log(level, timestamp, meta); // 这行用来调试 | |
| return `[${level.toUpperCase()}] ${timestamp} ${meta.ip} ${meta.path} ${meta.statusCode} ${message}`; | |
| }); | |
| const logger = winston.createLogger({ | |
| level: 'info', | |
| format: winston.format.combine( | |
| timestampInBeijing(), // 使用自定义时间戳格式化函数 | |
| myFormat | |
| ), | |
| defaultMeta: { service: 'user-service' }, | |
| transports: [ | |
| new winston.transports.File({ filename: 'error.log', level: 'error' }), | |
| new winston.transports.File({ filename: 'combined.log' }), | |
| ], | |
| }); | |
| if (process.env.NODE_ENV !== 'production') { | |
| logger.add(new winston.transports.Console({ | |
| format: winston.format.combine( | |
| winston.format.colorize(), | |
| timestampInBeijing(), // 使用自定义时间戳格式化函 | |
| myFormat | |
| ), | |
| })); | |
| } | |
| module.exports = logger; | |