第13章 监控与日志管理
13.1 监控指标
监控指标
连接指标
消息指标
性能指标
系统指标
客户端连接数
连接速率
断开速率
消息接收
消息发送
消息存储
消息延迟
吞吐量
队列深度
CPU使用率
内存使用
磁盘IO
13.2 系统主题监控
bash
# 实时监控脚本
#!/bin/bash
mosquitto_sub -v -t "$SYS/broker/#" | while read line; do
echo "$(date '+%Y-%m-%d %H:%M:%S') - $line"
done
监控仪表板
$SYS主题
Telegraf
InfluxDB
Grafana
可视化仪表板
13.3 日志管理
日志级别
日志级别
debug
info
notice
warning
error
最详细
最少
日志配置
bash
# /etc/mosquitto/mosquitto.conf
# 日志类型
log_dest file /var/log/mosquitto/mosquitto.log
log_dest syslog
log_dest stdout
log_dest topic
# 日志级别
log_type error
log_type warning
log_type notice
log_type information
# log_type debug
# 日志格式
log_timestamp true
log_timestamp_format %Y-%m-%dT%H:%M:%S
13.4 日志轮转
bash
# /etc/logrotate.d/mosquitto
/var/log/mosquitto/*.log {
daily
rotate 14
compress
delaycompress
missingok
notifempty
create 0640 mosquitto mosquitto
sharedscripts
postrotate
systemctl reload mosquitto > /dev/null 2>&1 || true
endscript
}
日志轮转流程
是
否
是
否
当前日志
每天检查
超过1天?
重命名+压缩
继续写入
保留14天
超过14天?
删除旧日志
保留
13.5 Prometheus监控
Exporter配置
bash
# 使用mosquitto-exporter
docker run -d \
--name mosquitto-exporter \
-p 9234:9234 \
sapcc/mosquitto-exporter \
--broker=mqtt://localhost:1883
Prometheus配置
yaml
# prometheus.yml
scrape_configs:
- job_name: 'mosquitto'
static_configs:
- targets: ['localhost:9234']
Grafana仪表板
Mosquitto
$SYS主题
Exporter
Prometheus
Grafana
监控面板
13.6 告警配置
yaml
# alertmanager.yml
routes:
- match:
alertname: MosquittoDown
receiver: 'email'
receivers:
- name: 'email'
email_configs:
- to: admin@example.com
from: alert@example.com
smarthost: smtp.example.com:587
告警规则
yaml
# mosquitto-alerts.yml
groups:
- name: mosquitto
rules:
- alert: MosquittoDown
expr: up{job="mosquitto"} == 0
for: 1m
labels:
severity: critical
annotations:
summary: "Mosquitto is down"
- alert: TooManyConnections
expr: mosquitto_clients_connected > 10000
for: 5m
labels:
severity: warning
13.7 本章小结
掌握了Mosquitto的监控和日志管理方法。