在 Debian 上 Node.js 日志的“编码”问题,通常分三种情况,对应不同改法。下面按常见场景说明。
Node.js 默认使用 UTF-8,但终端/系统环境可能不同。
locale
echo $LANG
如果是:
LANG=C
就可能不是 UTF-8。
sudo dpkg-reconfigure locales
勾选:
en_US.UTF-8
或
zh_CN.UTF-8
然后:
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
写入环境(永久):
echo 'export LANG=en_US.UTF-8' >> ~/.bashrc
如果你在代码里写日志:
fs.writeFileSync('app.log', '中文')
fs.writeFileSync('app.log', '中文', 'utf8')
const fs = require('fs')
const stream = fs.createWriteStream('app.log', { encoding: 'utf8' })
stream.write('中文日志')
✅ 只要不指定 binary / latin1,一般就是 UTF-8
PM2 日志默认 UTF-8,但如果系统 locale 不对:
pm2 restart all --update-env
或设置:
export LANG=en_US.UTF-8
pm2 startup
查看日志:
pm2 logs
编辑 service 文件:
sudo systemctl edit your-node.service
加入:
[Service]
Environment=LANG=en_US.UTF-8
Environment=LC_ALL=en_US.UTF-8
然后:
sudo systemctl daemon-reload
sudo systemctl restart your-node
const winston = require('winston')
const logger = winston.createLogger({
transports: [
new winston.transports.File({
filename: 'app.log',
options: { encoding: 'utf8' }
})
]
})
pino 默认 UTF-8,不要指定:
{ encoding: 'utf8' } // 默认就是这个
✅ 系统 locale 是 UTF-8
✅ Node.js 写文件用 utf8
✅ PM2 / systemd 环境变量正确
✅ 日志查看工具支持 UTF-8(如 cat, less)
如果你能告诉我:
我可以直接给你一份精确配置。