作为IT工程师,掌握Linux日志分析是系统管理和故障排查的核心技能。以下是全面的日志分析方法和故障排查流程:
系统日志:
/var/log/messages
- 常规系统活动日志/var/log/syslog
- 系统日志(基于Debian的系统)/var/log/auth.log
- 认证和安全相关日志服务日志:
/var/log/nginx/
- Nginx日志/var/log/apache2/
- Apache日志/var/log/mysql.log
- MySQL日志内核和启动日志:
/var/log/kern.log
- 内核日志/var/log/boot.log
- 系统启动日志/var/log/dmesg
- 内核环形缓冲区信息基础命令:
# 查看日志尾部
tail -f /var/log/syslog
# 查看日志头部
head -n 50 /var/log/messages
# 按时间筛选日志
sed -n '/2023-10-01 14:00/,/2023-10-01 15:00/p' /var/log/syslog
grep过滤:
# 查找错误信息
grep -i "error" /var/log/syslog
# 查找特定进程
grep "sshd" /var/log/auth.log
# 多条件搜索
grep -E "error|fail|critical" /var/log/messages
高级工具:
# 使用journalctl(systemd系统)
journalctl -u nginx --since "1 hour ago"
journalctl -p err -b
# 使用awk分析
awk '/Failed password/ {print $11}' /var/log/auth.log | sort | uniq -c | sort -nr
# 使用logrotate管理日志轮转
logrotate -vf /etc/logrotate.conf
确定问题时间范围:
date # 检查当前系统时间
uptime # 查看系统运行时间
last reboot # 查看重启历史
检查系统资源:
top # 动态查看进程
free -h # 内存使用
df -h # 磁盘空间
iostat -x 2 # I/O统计
网络问题排查:
netstat -tuln # 监听端口
ss -s # 套接字统计
tcpdump -i eth0 port 80 # 抓包分析
traceroute example.com # 路由追踪
服务状态检查:
systemctl status nginx # 服务状态
journalctl -u mysql --since "today" # 服务日志
时间关联分析:
# 找出特定时间段内的错误
sed -n '/Oct 1 10:00/,/Oct 1 11:00/p' /var/log/syslog | grep -i error
频率分析:
# 统计错误出现频率
grep "error" /var/log/messages | cut -d' ' -f1-3 | uniq -c
日志可视化:
# 生成访问量图表(需要gnuplot)
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -20 > /tmp/traffic
gnuplot -p -e 'plot "/tmp/traffic" using 1 with lines'
集中式日志管理:
日志轮转配置:
# 示例/etc/logrotate.d/nginx配置
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
/usr/sbin/nginx -s reload
endscript
}
日志监控告警:
掌握这些日志分析技能,您将能够快速定位和解决Linux系统中的各类问题,提高系统稳定性和安全性。