18. 日志分析与监控
本章介绍 RHEL 9 的日志管理体系与系统监控部署:rsyslog 集中日志转发与过滤、logrotate 日志轮转、logwatch 摘要报告,以及 Prometheus + Node Exporter + Grafana 可观测性栈的完整部署。完善的日志与监控体系是生产环境故障快速定位、安全审计与合规运营的核心基础设施。
18.1 前提条件
- 已完成第三阶段前序配置(第 15–17 章)。
- 通过 SecureCRT(SSH 端口 2222)以
ops用户、密钥认证方式登录192.168.1.100,执行sudo -i切换至 root 环境。 - EPEL 仓库已启用(第 7 章),SELinux 处于 Enforcing 模式,firewalld 已启用。
本章全局参数
| 参数 | 值 |
|---|---|
| 主机名 / IP | linuxdc / 192.168.1.100 |
| 远程日志服务器 | 192.168.1.200(syslog 端口 514) |
| Node Exporter 端口 | 9100 |
| Prometheus 端口 | 9090 |
| Grafana 端口 | 3000 |
| Grafana 默认账户 | admin / admin(首次登录强制修改) |
18.2 rsyslog 日志集中管理
rsyslog 是 RHEL 9 默认的系统日志守护进程,负责接收、过滤、路由和转发各类系统日志,与 systemd journal 协同工作,共同构成 RHEL 9 的双轨日志体系。
18.2.1 确认 rsyslog 服务状态
rpm -q rsyslog || dnf install -y rsyslog
systemctl enable --now rsyslog
systemctl status rsyslog
18.2.2 主要日志文件位置
# 查看 rsyslog 默认路由规则
grep -v "^#\|^$" /etc/rsyslog.conf | head -30
| 日志文件 | 内容 |
|---|---|
/var/log/messages |
系统通用日志(内核、服务等) |
/var/log/secure |
认证与安全日志(SSH 登录、sudo 操作) |
/var/log/maillog |
邮件系统日志 |
/var/log/cron |
定时任务日志 |
/var/log/dnf.log |
包管理操作日志 |
/var/log/audit/audit.log |
auditd 内核审计日志 |
18.2.3 配置自定义日志过滤规则
将特定服务日志写入独立文件,便于针对性分析与轮转管理:
tee /etc/rsyslog.d/50-linuxdc.conf << 'EOF'
# SSH 认证日志独立记录
:programname, isequal, "sshd" /var/log/sshd-auth.log
& stop
# sudo 操作日志独立记录
:programname, isequal, "sudo" /var/log/sudo-audit.log
& stop
EOF
systemctl restart rsyslog
# 验证:触发一条 sshd 日志
logger -t sshd "Test log from linuxdc"
tail -3 /var/log/sshd-auth.log
检查点
tail /var/log/sshd-auth.log 能看到刚写入的测试日志条目。
18.2.4 配置远程日志转发
将日志集中转发至日志服务器(192.168.1.200),满足等保合规的集中审计要求:
tee /etc/rsyslog.d/99-remote.conf << 'EOF'
# TCP 转发(推荐,有重传保障)
# @@ = TCP;@ = UDP(不可靠,生产不推荐)
*.* @@192.168.1.200:514
EOF
systemctl restart rsyslog
# 发送测试日志验证转发
logger -t linuxdc "Remote log test from 192.168.1.100"
TCP vs UDP 转发
生产环境必须使用 TCP(@@):TCP 有连接确认与重传机制,网络抖动时日志不丢失;若目标服务器不可达,可配置 queue.type="LinkedList" 启用异步队列缓冲,避免阻塞 rsyslog 主线程。集中式日志是等保二级及以上的基本要求。
18.2.5 配置日志轮转(logrotate)
# 查看 rsyslog 默认轮转配置
cat /etc/logrotate.d/syslog
# 为自定义日志文件配置轮转规则
tee /etc/logrotate.d/linuxdc-custom << 'EOF'
/var/log/sshd-auth.log
/var/log/sudo-audit.log
{
daily
rotate 30
compress
delaycompress
missingok
notifempty
postrotate
/usr/bin/systemctl kill -s HUP rsyslog.service > /dev/null 2>&1 || true
endscript
}
EOF
# 测试轮转配置(-d 仅模拟,不实际执行)
logrotate -d /etc/logrotate.d/linuxdc-custom
# 手动触发一次轮转(验证配置正确性)
logrotate -f /etc/logrotate.d/linuxdc-custom
ls -lh /var/log/sshd-auth.log*
logrotate 关键参数说明:
| 参数 | 含义 |
|---|---|
daily |
每日轮转 |
rotate 30 |
保留 30 个轮转文件 |
compress |
压缩旧日志(gzip) |
delaycompress |
延迟一轮再压缩(避免压缩仍在写入的文件) |
missingok |
日志文件不存在时不报错 |
notifempty |
日志为空时不轮转 |
postrotate |
轮转后向 rsyslog 发送 HUP 信号,使其重新打开日志文件 |
18.3 logwatch 日志摘要报告
logwatch 对系统日志进行聚合分析,生成可读性强的摘要报告,适合每日运维巡检。
18.3.1 安装与基础使用
dnf install -y logwatch
# 生成今日所有服务的中等详细度摘要报告
logwatch --detail Med --range today --output stdout
# 生成昨日 sshd 服务的高详细度报告
logwatch --service sshd --detail High --range yesterday --output stdout
# 保存报告到文件
logwatch --detail Med --range yesterday --output file \
--filename /tmp/logwatch-$(date +%F).txt
cat /tmp/logwatch-$(date +%F).txt
18.3.2 配置每日自动报告
# logwatch 默认在 /etc/cron.daily/ 中已有执行脚本
ls -la /etc/cron.daily/ | grep logwatch
# 自定义配置(创建本地覆盖文件)
tee /etc/logwatch/conf/logwatch.conf << 'EOF'
Output = stdout
Format = text
Encode = none
MailTo = root
Detail = Med
Range = yesterday
Service = All
EOF
18.4 Prometheus + Node Exporter 指标监控
Prometheus 是目前最流行的开源监控系统,采用拉取(Pull)模型定期从各 Exporter 抓取指标;Node Exporter 负责采集主机级别的系统指标(CPU、内存、磁盘、网络等)。
部署说明
本节在 linuxdc(192.168.1.100)上同机部署 Node Exporter、Prometheus Server 和 Grafana,用于演示完整链路。生产环境中 Prometheus Server 和 Grafana 应部署在独立的监控服务器上,避免被监控节点故障时监控系统同步失效。
18.4.1 安装并启动 Node Exporter
dnf install -y golang-github-prometheus-node-exporter
systemctl enable --now node_exporter
systemctl status node_exporter
开放防火墙端口:
firewall-cmd --permanent --add-port=9100/tcp
firewall-cmd --reload
验证指标端点:
curl -s http://localhost:9100/metrics | head -20
curl -s http://localhost:9100/metrics | grep "^node_cpu_seconds_total" | head -5
检查点
curl http://localhost:9100/metrics 返回以 # HELP 和 # TYPE 开头的 Prometheus 格式指标数据,说明 Node Exporter 工作正常。
18.4.2 安装并配置 Prometheus Server
dnf install -y prometheus
编辑 Prometheus 配置,添加 Node Exporter 抓取目标:
vim /etc/prometheus/prometheus.yml
在 scrape_configs 节中添加:
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'linuxdc-node'
scrape_interval: 15s
static_configs:
- targets: ['192.168.1.100:9100']
relabel_configs:
- source_labels: [__address__]
target_label: instance
replacement: 'linuxdc'
systemctl enable --now prometheus
# 开放 Prometheus 端口(生产中应仅允许 Grafana 所在 IP 访问)
firewall-cmd --permanent --add-port=9090/tcp
firewall-cmd --reload
# 验证 Prometheus 已开始抓取指标
curl -s http://localhost:9090/api/v1/targets \
| python3 -m json.tool | grep '"health"'
检查点
API 返回中 "health": "up" 说明 Prometheus 已成功抓取 Node Exporter 指标。
18.4.3 配置磁盘使用率告警规则
mkdir -p /etc/prometheus/rules
tee /etc/prometheus/rules/disk-alerts.yml << 'EOF'
groups:
- name: disk_alerts
rules:
- alert: DiskUsageHigh
expr: >
100 - (node_filesystem_avail_bytes{mountpoint="/",fstype!="tmpfs"}
* 100 / node_filesystem_size_bytes{mountpoint="/",fstype!="tmpfs"}) > 80
for: 5m
labels:
severity: warning
annotations:
summary: "磁盘使用率过高 ({{ $labels.instance }})"
description: "根分区使用率超过 80%,当前值: {{ $value | printf \"%.1f\" }}%"
- alert: DiskUsageCritical
expr: >
100 - (node_filesystem_avail_bytes{mountpoint="/",fstype!="tmpfs"}
* 100 / node_filesystem_size_bytes{mountpoint="/",fstype!="tmpfs"}) > 90
for: 2m
labels:
severity: critical
annotations:
summary: "磁盘使用率严重告警 ({{ $labels.instance }})"
description: "根分区使用率超过 90%,当前值: {{ $value | printf \"%.1f\" }}%"
EOF
# 在 prometheus.yml 中引入告警规则目录
grep -q "rule_files" /etc/prometheus/prometheus.yml || \
sed -i '/^global:/i rule_files:\n - "rules/*.yml"\n' /etc/prometheus/prometheus.yml
systemctl restart prometheus
18.5 Grafana 可视化面板
18.5.1 安装 Grafana
# 添加 Grafana 官方 YUM 仓库
tee /etc/yum.repos.d/grafana.repo << 'EOF'
[grafana]
name=grafana
baseurl=https://packages.grafana.com/oss/rpm
repo_gpgcheck=1
enabled=1
gpgcheck=1
gpgkey=https://packages.grafana.com/gpg.key
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
EOF
dnf install -y grafana
systemctl enable --now grafana-server
开放防火墙端口:
firewall-cmd --permanent --add-port=3000/tcp
firewall-cmd --reload
验证服务已启动:
systemctl status grafana-server
ss -tuln | grep :3000
18.5.2 初始化配置
通过浏览器访问:http://192.168.1.100:3000
- 默认账户:
admin/admin - 首次登录会强制要求修改密码,设置符合组织密码策略的强密码。
添加 Prometheus 数据源:
- 左侧菜单 → Connections → Data Sources → Add data source
- 选择 Prometheus
- Connection URL 填写:
http://localhost:9090 - 点击 Save & Test,提示
Data source is working即成功
导入 Node Exporter 预置仪表盘:
- 左侧菜单 → Dashboards → Import
- 在
Import via grafana.com输入 Dashboard ID:1860(Node Exporter Full) - 选择已添加的 Prometheus 数据源
- 点击 Import
检查点
Grafana 仪表盘正常加载,显示 linuxdc(192.168.1.100)的 CPU 使用率、内存使用量、磁盘 I/O、网络流量等实时图表。
18.5.3 SELinux 配置(Grafana 访问 Prometheus)
# 若 Grafana 无法连接 Prometheus(SELinux 可能阻止本机 HTTP 连接)
setsebool -P httpd_can_network_connect on
# 验证 SELinux 不再阻止连接
ausearch -m avc -ts recent | grep grafana
18.6 常见问题与排查
| 问题现象 | 排查步骤 |
|---|---|
| rsyslog 日志未写入自定义文件 | rsyslogd -N1 验证配置语法;systemctl restart rsyslog 后重新测试 |
| rsyslog 远程转发失败 | nc -zv 192.168.1.200 514 测试网络连通性;检查目标服务器防火墙 |
| Node Exporter 无法访问 | systemctl status node_exporter;firewall-cmd --list-ports 确认 9100 已开放 |
| Prometheus 抓取目标显示 DOWN | curl http://192.168.1.100:9100/metrics 验证 Node Exporter;检查防火墙和 SELinux |
| Grafana 数据源连接失败 | curl http://localhost:9090/-/healthy 验证 Prometheus;执行 setsebool -P httpd_can_network_connect on |
| Grafana 面板数据为空 | 检查数据源 URL;验证 scrape_interval 配置;在 Prometheus UI 手动查询指标 |
# rsyslog 配置语法验证
rsyslogd -N1
# Prometheus 目标状态 API
curl -s http://localhost:9090/api/v1/targets | python3 -m json.tool
# Grafana 日志
journalctl -u grafana-server -n 30
# Prometheus 日志
journalctl -u prometheus -n 30
18.7 实践任务
- 登录
linuxdc(SecureCRT 端口 2222,ops用户,密钥认证,sudo -i切换 root)。 - 创建
/etc/rsyslog.d/50-linuxdc.conf,将 sshd 日志独立写入/var/log/sshd-auth.log,触发测试日志验证生效。 - 配置
/etc/logrotate.d/linuxdc-custom,手动触发轮转,验证旧日志已压缩。 -
手动生成 logwatch 报告:
logwatch --service sshd --detail High --range today --output stdout -
安装并启动 Node Exporter,验证指标端点:
curl -s http://localhost:9100/metrics | grep "^node_load1" -
安装 Prometheus,配置抓取
linuxdc的 Node Exporter,验证 target 状态为 UP。 - 安装 Grafana,添加 Prometheus 数据源,导入 Dashboard ID 1860,确认面板正常显示。
18.8 自测问题
Q1:rsyslog 使用 @(UDP)与 @@(TCP)转发有什么本质区别,生产应选哪个?
UDP 无连接无确认,速度快但不可靠,网络丢包时日志直接丢失;TCP 有连接握手与重传机制,日志传输有保障。生产环境必须使用 TCP(@@)——日志的完整性是安全审计与合规的基础,不可因追求性能而牺牲可靠性。
Q2:Prometheus 的 scrape_interval 过短会有什么负面影响?
过短的采集间隔(如 5s)会大幅增加 Node Exporter 的计算开销、Prometheus 的写入频率和磁盘占用,对被监控节点产生额外压力。推荐通用系统指标使用默认 15s,对延迟敏感的关键指标可针对性设为 5–10s,避免全局缩短导致整体资源消耗过高。
Q3:为什么生产环境中 Grafana 应与 Prometheus 分离部署在不同服务器?
若监控系统与被监控业务服务部署在同一主机,当该主机出现故障或高负载时,监控系统本身也随之不可用,正是最需要监控数据的时候反而看不到任何信息,失去了监控的根本意义。独立的监控服务器能在被监控节点异常时保持正常工作,从外部视角持续观察目标节点的状态变化。
18.9 章节总结
本章构建了 RHEL 9 的完整可观测性体系:rsyslog 日志分类过滤与集中转发(TCP 推送,含 queue 缓冲配置建议);logrotate 自动轮转管理(压缩、保留、HUP 信号重载);logwatch 每日摘要巡检报告;Prometheus + Node Exporter 指标采集(含磁盘使用率告警规则);Grafana 可视化面板(Dashboard 1860 一键导入)。日志与指标的双维度覆盖,是生产环境运维可靠性和等保合规的核心保障,也为第 19 章的硬盘专项监控提供了完整的基础设施支撑。