Linux · 2 分钟阅读
Linux 日志管理
2026 年现状:systemd-journald 已经是绝大多数发行版的默认日志后端,rsyslog 更多作为中转/转发角色。
journalctl是日常排错的主入口。
核心路径
| 文件 / 服务 | 内容 |
|---|---|
/var/log/messages |
系统通用日志(RHEL 系) |
/var/log/syslog |
同上(Debian 系) |
/var/log/auth.log / secure |
认证相关 |
/var/log/kern.log |
内核 |
/var/log/cron |
计划任务 |
/var/log/nginx/, /var/log/httpd/ |
Web 服务 |
/var/log/mysql/ |
MySQL / MariaDB |
journalctl |
systemd journal |
journalctl 速查
journalctl # 全部
journalctl -u nginx # 单服务
journalctl -u nginx -f # follow
journalctl -u nginx -n 200 # 最近 200 行
journalctl -u nginx --since "1 hour ago"
journalctl -u nginx --since "2026-08-01" --until "2026-08-04"
journalctl -p err # 错误及以上
journalctl _PID=1234
journalctl -k # 内核
journalctl --vacuum-time=7d # 清理 7 天前
rsyslog(老牌转发)
# /etc/rsyslog.d/remote.conf
*.* @remote-host:514 # UDP
*.* @@remote-host:514 # TCP
systemctl restart rsyslog
集中日志现代方案是 Vector / Promtail / Filebeat,rsyslog 仍能工作但偏老派。
logrotate
# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
rotate 14
compress
delaycompress
missingok
notifempty
create 0640 nginx nginx
sharedscripts
postrotate
systemctl reload nginx
endscript
}
logrotate -d /etc/logrotate.d/nginx # 调试
logrotate -f /etc/logrotate.d/nginx # 强制执行
分析命令
# 实时 + 关键字高亮
tail -F /var/log/nginx/access.log | grep --color=auto ' 5[0-9][0-9] '
# 统计访问 IP 排行
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head
# 错误数 / 分钟
grep -c "ERROR" app.log
# 按时间窗口
sed -n '/Aug 4 10:00/,/Aug 4 11:00/p' /var/log/messages
处理 JSON / 结构化日志,用
lnav或q,比grep直观。
监控脚本
#!/bin/bash
# /usr/local/bin/log-watch.sh
WATCH_LOG=/var/log/app/app.log
SIZE=$(stat -c%s "$WATCH_LOG")
MAX=$((100 * 1024 * 1024)) # 100 MB
if (( SIZE > MAX )); then
logger -t log-watch "WARN: $WATCH_LOG too large: $SIZE"
fi
远程日志
# /etc/rsyslog.d/10-forward.conf
*.* action(type="omfwd" target="logserver.internal" port="514" protocol="tcp")
更现代的方案:
# Filebeat 推送到 ELK
filebeat -e -c /etc/filebeat/filebeat.yml
# Vector 推送到 Loki
vector --config /etc/vector/vector.toml
安全与合规
- 日志权限
640+ 属主root:adm/root:wheel - 关键日志(GPG / 加密)落远程
- 保留期写进 logrotate 策略,按合规要求(PCI、GDPR)执行
- 篡改检测:
aide/tripwire监控关键日志的哈希