LAMP在CentOS上的日志管理技巧
在CentOS的LAMP(Linux、Apache、MySQL、PHP)环境中,各组件的日志文件集中存储在/var/log/目录下,明确路径是管理的基础:
/var/log/httpd/access_log(记录所有用户请求)、错误日志/var/log/httpd/error_log(记录服务器运行错误);/var/log/mysqld.log(默认错误信息)、慢查询日志/var/log/mysql/slow-queries.log(需手动开启,记录执行时间超过阈值的SQL)、通用查询日志/var/log/mysql/query.log(记录所有SQL语句,调试用);/var/log/php-fpm/error.log;若集成在Apache中,则错误信息会写入Apache的error_log;/var/log/messages、安全相关事件(登录、sudo使用)/var/log/secure。针对不同场景选择高效命令,快速定位问题:
tail -f /var/log/httpd/error_log实时跟踪Apache错误日志的最新条目,适合监控实时问题;grep "ERROR" /var/log/httpd/error_log筛选包含“ERROR”的错误日志,或结合管道journalctl | grep "mysql"搜索systemd日志中的MySQL相关记录;less /var/log/mysqld.log分页浏览大型日志文件,支持上下翻页和搜索(按/键输入关键词);journalctl -b查看本次系统启动后的日志,journalctl -b -1查看上一次启动的日志,journalctl -k查看内核日志。使用logrotate工具自动管理日志文件的轮转(压缩、删除旧日志),防止日志占用过多磁盘空间。以Apache为例,配置文件通常位于/etc/logrotate.d/httpd,内容示例如下:
/var/log/httpd/*.log {
daily # 每日轮转
missingok # 若日志文件不存在也不报错
rotate 7 # 保留最近7个轮转文件
compress # 压缩旧日志(如access_log.1.gz)
delaycompress # 延迟压缩(如access_log.1不压缩,access_log.2.gz压缩)
notifempty # 若日志为空则不轮转
create 640 root adm # 创建新日志文件并设置权限(用户:root,组:adm)
}
手动触发轮转测试:logrotate -vf /etc/logrotate.d/httpd(-v显示详细过程,-f强制轮转)。
awk提取特定字段,如统计Apache访问日志中的IP访问次数(找出高频访问IP):awk '{print $1}' /var/log/httpd/access_log | sort | uniq -c | sort -nr | head -10
用sort和uniq去重统计,如找出MySQL慢查询日志中的高频慢查询:grep "Query_time" /var/log/mysql/slow-queries.log | awk '{print $4}' | sort | uniq -c | sort -nr
chmod和chown设置日志文件权限,确保只有授权用户可访问。例如:chmod 640 /var/log/httpd/error_log # 用户可读写,组可读,其他无权限
chown root:adm /var/log/httpd/error_log # 所有者:root,组:adm
192.168.1.100),编辑/etc/rsyslog.conf添加:*.* @192.168.1.100:514 # UDP传输
# *.* @@192.168.1.100:514 # TCP传输(更可靠)
重启rsyslog服务:systemctl restart rsyslog。logrotate的maxage参数设置日志保留天数(如maxage 30保留30天),或用find命令手动清理:find /var/log -name "*.log" -mtime +30 -exec rm -f {} \; # 删除30天前的.log文件
tail -f结合mail命令在检测到“ERROR”时发送邮件告警:tail -f /var/log/httpd/error_log | grep --line-buffered "ERROR" | while read line; do echo "$line" | mail -s "Apache Error Alert" admin@example.com; done