rsyslog (现代Linux默认日志服务)
/etc/rsyslog.conf
/etc/rsyslog.d/
sudo systemctl restart rsyslog
sudo tail -f /var/log/syslog
journald (systemd系统的日志服务)
journalctl -xe
journalctl -u nginx.service --since "2023-01-01" --until "2023-01-02"
安装配置:
# Elasticsearch
wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-8.4.3-amd64.deb
sudo dpkg -i elasticsearch-8.4.3-amd64.deb
# Logstash
wget https://artifacts.elastic.co/downloads/logstash/logstash-8.4.3.deb
sudo dpkg -i logstash-8.4.3.deb
# Kibana
wget https://artifacts.elastic.co/downloads/kibana/kibana-8.4.3-amd64.deb
sudo dpkg -i kibana-8.4.3-amd64.deb
配置文件示例 (/etc/filebeat/filebeat.yml
):
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/*.log
- /var/log/nginx/*.log
output.logstash:
hosts: ["localhost:5044"]
grep: 文本搜索
grep "ERROR" /var/log/syslog
awk: 文本处理
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr
sed: 流编辑器
sed -n '/Jan 10 10:17/,/Jan 10 10:18/p' /var/log/syslog
logrotate: 日志轮转
sudo logrotate -f /etc/logrotate.conf
Logstash 配置示例:
input {
beats {
port => 5044
}
}
filter {
grok {
match => { "message" => "%{COMBINEDAPACHELOG}" }
}
geoip {
source => "clientip"
}
}
output {
elasticsearch {
hosts => ["localhost:9200"]
index => "apache-%{+YYYY.MM.dd}"
}
}
Kibana 可视化:
日志轮转策略
/etc/logrotate.d/nginx
):
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
/usr/bin/systemctl reload nginx
endscript
}
日志安全
chmod 640 /var/log/sensitive.log
性能优化
磁盘空间不足
# 查找大日志文件
sudo find /var/log -type f -size +100M -exec ls -lh {} \;
# 清空日志文件(不删除文件)
sudo truncate -s 0 /var/log/large.log
日志服务不工作
# 检查服务状态
sudo systemctl status rsyslog
# 检查配置文件语法
sudo rsyslogd -N1
日志分析性能问题
通过以上方法和工具,您可以有效地收集、管理和分析Linux系统日志,从而提高系统监控能力和故障排查效率。