优化CentOS系统日志的方法
journalctl是systemd提供的日志管理工具,可高效清理和轮转systemd-journald生成的日志(默认存储在/var/log/journal/)。常用命令:
journalctl --vacuum-time=7d;journalctl --vacuum-size=500M;rm -rf /var/log/journal/*。logrotate是CentOS默认的日志轮转工具,可自动压缩、删除旧日志,防止日志文件过大。操作步骤:
sudo yum install logrotate -y;/etc/logrotate.d/rsyslog(系统日志)或创建新配置文件(如/etc/logrotate.d/myapp),示例配置:/var/log/myapp.log {
daily # 每天轮转
rotate 7 # 保留7个旧日志
compress # 压缩旧日志(gzip)
delaycompress # 延迟压缩(下一次轮转时压缩前一天的日志)
missingok # 日志文件不存在时不报错
notifempty # 日志为空时不轮转
create 0640 root root # 创建新日志的权限和所有者
}
logrotate -d /etc/logrotate.conf调试配置(模拟运行),用logrotate -f /etc/logrotate.conf强制立即轮转。rsyslog是CentOS默认的日志收集服务,通过调整日志级别可减少不必要的日志输出。操作步骤:
/etc/rsyslog.conf或/etc/rsyslog.d/下的自定义配置文件;*.info(记录所有信息)改为*.err(仅记录错误),示例:*.err;kern.debug;auth.notice;authpriv.notice /dev/console
systemctl restart rsyslog使配置生效。部分服务(如messagebus)的日志可能无实际用途,禁用后可减少日志量。操作步骤:
/usr/lib/systemd/system/messagebus.service(或/etc/systemd/system/messagebus.service);[Service]部分添加:StandardOutput=null
StandardError=null
systemctl daemon-reload && systemctl restart messagebus。通过调整systemd-journald的存储参数,可直接控制日志的大小和保留时间。操作步骤:
/etc/systemd/journald.conf;SystemMaxUse=500M # 日志最大占用空间(500MB)
SystemKeepFree=100M # 保留的空闲空间(100MB)
SystemMaxFileSize=100M # 单个日志文件最大大小(100MB)
MaxRetentionSec=7day # 日志保留时间(7天)
systemctl restart systemd-journald使配置生效。定期监控日志文件的大小和系统性能,及时发现异常。常用工具:
sysstat后执行sar -f /var/log/sa/saXX(XX为日期)查看日志文件增长情况;/etc/logwatch/conf/logwatch.conf,可发送每日日志摘要到邮箱,示例配置:Service = myapp
Detail = High
Range = yesterday
Output = mail
MailTo = your_email@example.com
监控可帮助提前预警日志增长过快的问题,避免磁盘空间耗尽。