43 lines
1.2 KiB
JavaScript
43 lines
1.2 KiB
JavaScript
const winston = require('winston');
|
|
|
|
const logger = winston.createLogger({
|
|
level: 'info',
|
|
format: winston.format.combine(
|
|
winston.format.timestamp({
|
|
format: 'YYYY-MM-DD HH:mm:ss',
|
|
tz: 'Asia/Shanghai'
|
|
}),
|
|
winston.format.errors({ stack: true }),
|
|
winston.format.splat(),
|
|
winston.format.json()
|
|
),
|
|
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(),
|
|
// 确保控制台日志也有正确格式和时区的时间戳
|
|
winston.format.timestamp({
|
|
format: 'YYYY-MM-DD HH:mm:ss',
|
|
tz: 'Asia/Shanghai'
|
|
}),
|
|
winston.format.printf(({ level, message, timestamp, stack }) => {
|
|
if (stack) {
|
|
// 打印错误堆栈
|
|
return `${timestamp} ${level}: ${message}\n${stack}`;
|
|
}
|
|
return `${timestamp} ${level}: ${message}`;
|
|
})
|
|
)
|
|
}));
|
|
}
|
|
|
|
module.exports = logger;
|