Spaces:
Running
Running
File size: 1,296 Bytes
06aa7f8 b1427d6 06aa7f8 b1427d6 4e2eb63 a666717 06aa7f8 b1427d6 06aa7f8 a26bed7 06aa7f8 b1427d6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
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;
|