Linux 日志出现“编码异常”通常指日志里出现乱码、问号 ?、方块、或者非 UTF-8 字符。下面按常见原因 → 对应解决办法来说明。
file -i /var/log/messages
# 或
enca /var/log/syslog
常见情况:
UTF-8 ✅ 正常ISO-8859-1 / GBK / ANSI ❌ 易乱码现象:cat 看是乱码,但文件本身没问题
✅ 解决:
export LANG=zh_CN.UTF-8
export LC_ALL=zh_CN.UTF-8
永久生效:
# CentOS / RHEL
localectl set-locale LANG=zh_CN.UTF-8
# 或写入
echo 'export LANG=zh_CN.UTF-8' >> ~/.bashrc
例如 Java / Python / C++ 程序输出 GBK
✅ 解决:
-Dfile.encoding=UTF-8
import sys
sys.setdefaultencoding('utf-8') # Python2
# Python3 默认 UTF-8
setlocale(LC_ALL, "zh_CN.UTF-8");
✅ 转换编码:
iconv -f GBK -t UTF-8 old.log -o new.log
批量:
for f in *.log; do
iconv -f GBK -t UTF-8 "$f" -o "$f.utf8"
done
✅ 查看:
journalctl -u nginx
若乱码:
sudo vim /etc/systemd/journald.conf
修改:
[Journal]
Storage=persistent
然后:
sudo systemctl restart systemd-journald
rsyslog
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat
确保系统语言是 UTF-8
filebeat
encoding: utf-8
✅ 安装中文语言包:
# CentOS
yum install -y glibc-langpack-zh
# Ubuntu
apt install -y language-pack-zh-hans
✅ 终端 UTF-8
✅ 系统 LANG=UTF-8
✅ 程序输出 UTF-8
✅ 日志文件 UTF-8
✅ 采集工具 UTF-8
你可以发我:
cat /etc/os-release)我可以直接给你针对性命令。