Linux进阶之系统监控与日志管理
系统监控和日志管理是 Linux 系统运维的重要组成部分。本章将详细讲解 Prometheus 和 Grafana 的监控配置,以及 Logrotate 和 ELK(Elasticsearch、Logstash、Kibana)的日志管理。
一、Linux 系统监控
1、Prometheus 与 Grafana 概述
Prometheus
Prometheus 是一款开源监控和告警工具,专为时间序列数据存储和分析设计,常用于监控系统性能和应用状态。
Grafana
Grafana 是一款数据可视化工具,可以将 Prometheus 等数据源的数据展示为可交互的仪表盘。
2、Prometheus 配置
安装 Prometheus
在 Debian/Ubuntu 系统上:
sudo apt update
sudo apt install prometheus -y
在 CentOS/RHEL 系统上:
sudo yum install prometheus -y
配置 Prometheus
Prometheus 的主配置文件为 /etc/prometheus/prometheus.yml
,编辑以下内容:
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'linux_servers'
static_configs:
- targets: ['localhost:9090']
启动并启用 Prometheus:
sudo systemctl start prometheus
sudo systemctl enable prometheus
验证 Prometheus
在浏览器中访问 http://<服务器IP>:9090
,进入 Prometheus 的 web 界面。
3、Grafana 配置
安装 Grafana
在 Debian/Ubuntu 系统上:
sudo apt install -y grafana
在 CentOS/RHEL 系统上:
sudo yum install -y grafana
配置 Grafana
启动并启用 Grafana 服务:
sudo systemctl start grafana-server
sudo systemctl enable grafana-server
在浏览器访问 http://<服务器IP>:3000
,使用默认账户 admin/admin
登录。
集成 Prometheus 数据源
- 在 Grafana Web 界面中,导航到 Configuration > Data Sources。
- 点击 Add data source,选择 Prometheus。
- 输入 Prometheus 地址(如
http://localhost:9090
),保存配置。
创建仪表盘
通过 Dashboard > New Dashboard 添加自定义监控面板,并选择 Prometheus 提供的监控指标。
二、日志管理
1、Logrotate 日志轮转与压缩
Logrotate 简介
Logrotate 是一个日志管理工具,用于自动压缩、轮转和删除过期日志。
配置 Logrotate
Logrotate 的主配置文件为 /etc/logrotate.conf
,单独服务的配置通常位于 /etc/logrotate.d/
目录。
以下是一个典型配置示例:
/var/log/syslog {
weekly
rotate 4
compress
delaycompress
missingok
notifempty
}
手动测试 Logrotate
运行以下命令测试配置:
sudo logrotate -vf /etc/logrotate.conf
2、ELK 日志管理套件
ELK 简介
- Elasticsearch:存储和搜索日志数据。
- Logstash:收集和处理日志。
- Kibana:可视化日志数据。
安装 Elasticsearch
在 Debian/Ubuntu 系统上:
sudo apt install elasticsearch -y
配置并启动服务:
sudo systemctl start elasticsearch
sudo systemctl enable elasticsearch
验证服务运行状态:
curl -X GET "localhost:9200"
安装 Logstash
在 Debian/Ubuntu 系统上:
sudo apt install logstash -y
编辑 /etc/logstash/conf.d/logstash.conf
:
input {
file {
path => "/var/log/syslog"
start_position => "beginning"
}
}
output {
elasticsearch {
hosts => ["localhost:9200"]
}
stdout { codec => rubydebug }
}
启动 Logstash:
sudo systemctl start logstash
sudo systemctl enable logstash
安装 Kibana
在 Debian/Ubuntu 系统上:
sudo apt install kibana -y
配置并启动服务:
sudo systemctl start kibana
sudo systemctl enable kibana
在浏览器访问 http://<服务器IP>:5601
进入 Kibana 界面。
在 Kibana 中添加索引
- 导航到 Management > Index Patterns。
- 创建一个新的索引模式,如
logstash-*
。 - 开始使用 Discover 功能查看日志。
三、小结
通过本章学习,你掌握了以下内容:
- Prometheus 与 Grafana:实现系统和服务监控。
- Logrotate:实现日志的自动轮转和压缩。
- ELK:提供全面的日志存储、处理和可视化。
无论是监控还是日志管理,都能为系统运维提供更强的保障,助力 Linux 系统的高效运维与问题排查。