温馨提示×

CentOS Syslog如何排查系统问题

小樊
41
2025-12-21 11:25:56
栏目: 智能运维

CentOS Syslog 排查系统问题的实用流程

一 快速定位与实时查看

  • 确认日志服务运行状态并查看启动日志:
    • 检查服务:systemctl status rsyslog
    • 查看启动与运行日志:journalctl -u rsyslog
  • 实时查看系统日志与内核日志:
    • 传统文件:tail -f /var/log/messagestail -f /var/log/securetail -f /var/log/kern.log
    • systemd 日志:journalctl -f
  • 按时间窗口定位:
    • 当前启动:journalctl -b
    • 上一次启动:journalctl -b -1
    • 指定时间段:journalctl --since “2025-12-21 10:00:00” --until “2025-12-21 11:00:00”
  • 按服务定位:
    • 指定服务:journalctl -u nginxjournalctl -u sshd
  • 关键字筛选与高亮:
    • 过滤错误:grep -i “error|fail|fatal” /var/log/messages
    • 带行号:grep -n “failed” /var/log/messages
    • 实时过滤:tail -f /var/log/messages | grep --line-buffered “ERROR”

二 常见故障场景与排查要点

  • 服务未写日志或启动失败
    • 确认服务运行:systemctl status rsyslog
    • 查看启动报错:journalctl -u rsyslog -xe
    • 重启生效:systemctl restart rsyslog
  • 远程日志不通(客户端→服务器)
    • 客户端发送示例(UDP):在 /etc/rsyslog.conf 添加规则:. @192.0.2.10:514”;如使用 TCP 用 “@@”
    • 服务器监听(UDP):在 /etc/rsyslog.conf 启用模块与端口:$ModLoad imudp$UDPServerRun 514
    • 防火墙放行:
      • CentOS 7:firewall-cmd --permanent --add-port=514/udp && firewall-cmd --reload
      • 或按服务放行:firewall-cmd --permanent --add-service=syslog && firewall-cmd --reload
    • 连通性测试:
      • 端口可达:nc -vzu 192.0.2.10 514
      • 发送测试日志:logger -p user.info “rsyslog-test”,在服务器 /var/log/messages 或按客户端 IP 分割的目录中查看
  • 日志量过大或轮转异常
    • 检查轮转配置:/etc/logrotate.conf/etc/logrotate.d/,确认 weekly/rotate 4/create/compress 等策略
    • 手动触发测试:logrotate -d /etc/logrotate.conf(干跑),logrotate -f /etc/logrotate.conf(强制执行)
  • 内核与硬件线索
    • 查看内核环缓冲:dmesg | tail -n 50
    • 启动阶段日志:journalctl -k
    • 硬件健康:smartctl -a /dev/sda;内存检测可用 memtest86+(需重启进入)

三 高效检索与分析技巧

  • 字段提取与统计
    • 提取时间与进程:awk ‘{print $1,$2,$3,$6}’ /var/log/messages
    • 错误计数:grep -i error /var/log/messages | wc -l
    • 按进程统计错误:grep -i error /var/log/messages | awk ‘{print $6}’ | sort | uniq -c | sort -nr | head
  • 时间线定位
    • 某时段错误:journalctl --since “10:00” --until “11:00” | grep -i error
    • 服务重启前后:journalctl -u nginx --since “2025-12-21 09:55:00” -p err
  • 模式过滤与去重
    • 忽略大小写与重复行:grep -i “fail” /var/log/messages | sort -u
    • 复杂过滤:sed ‘/^$/d’ /var/log/messages | grep “timeout”
  • 报表与可视化
    • 生成日报:logwatch --range Yesterday --detail high
    • 集中分析与可视化:ELK Stack(Elasticsearch/Logstash/Kibana)GraylogSplunk

四 最小可用配置示例

  • 客户端:将本机所有日志以 UDP 发送到日志服务器 192.0.2.10
    • 编辑 /etc/rsyslog.conf,在末尾添加:. @192.0.2.10:514”
    • 重启:systemctl restart rsyslog
    • 测试:logger -p user.info “client-to-server-test”
  • 服务器:接收 UDP 日志并按客户端 IP 分目录保存
    • 编辑 /etc/rsyslog.conf
      • 启用 UDP:$ModLoad imudp$UDPServerRun 514
      • 按 IP 模板:$template IpTemplate,“/var/log/%FROMHOST-IP%.log”
      • 应用模板:. ?IpTemplate
    • 防火墙放行:firewall-cmd --permanent --add-port=514/udp && firewall-cmd --reload
    • 重启:systemctl restart rsyslog
    • 验证:tail -f /var/log/192.0.2.*.log 应能看到客户端测试日志

0