Winston控制台日志输出未对齐问题排查求助
Winston日志对齐问题:添加
align()后仍未对齐 我用Winston Logger配置日志输出,已经加了align()格式化项,但控制台日志还是没对齐。下面是我的配置代码和实际输出,请问问题出在哪?
配置代码
export default function getLogger(filename) { const config = { level: process.env.LOG_LEVEL || "info", defaultMeta: { service: filename, }, format: combine( colorize({ all: true }), timestamp({ format: "YYYY-MM-DD hh:mm:ss.SSS A", }), align(), printf( (info) => `[${info.timestamp}] [${info.service}] ${info.level}: ${info.message}` ) ), transports: [new winston.transports.Console()], }; const logger = winston.createLogger(config); return logger; }
实际输出
[2024-03-16 05:13:34.799 PM] [app.js] info: Database connected. [2024-03-16 05:13:34.801 PM] [app.js] info: Server running on port 3000 [2024-03-16 05:13:56.041 PM] [autenticate.js] error: Autenticaion failed
问题原因及解决办法
问题出在**align()的执行逻辑和自定义printf的冲突**:
align()的作用是给info.message添加缩进对齐,但你在printf里手动拼接了所有内容,align()的处理结果被完全覆盖,根本没生效。- 另外,
service(比如app.js和autenticate.js)、level(info是4字符,error是5字符)的字段长度不一致,也会导致整体排版错位。
修复方案
方案1:手动固定字段宽度
修改printf函数,用字符串填充方法把service和level统一为固定宽度,适配颜色字符的影响:
printf((info) => { // 将service字段填充到15字符宽度,不足补空格 const fixedService = info.service.padEnd(15, ' '); // level字段因colorize添加了ANSI颜色码,预留7字符宽度确保对齐 const fixedLevel = info.level.padEnd(7, ' '); return `[${info.timestamp}] [${fixedService}] ${fixedLevel}: ${info.message}`; })
方案2:用Winston自带的padLevels()处理level对齐
配合固定service宽度,更简洁:
format: combine( colorize({ all: true }), timestamp({ format: "YYYY-MM-DD hh:mm:ss.SSS A", }), padLevels(), // 自动对齐level字段 printf((info) => { const fixedService = info.service.padEnd(15, ' '); return `[${info.timestamp}] [${fixedService}] ${info.level}: ${info.message}`; }) ),
内容的提问来源于stack exchange,提问作者Cody
相关产品推荐
相关产品推荐

