温馨提示×

CentOS下nginx日志管理策略

小樊
46
2025-09-03 22:21:45
栏目: 智能运维

一、日志配置

  • 路径与格式:默认路径为/var/log/nginx/,通过修改/etc/nginx/nginx.conf可自定义日志格式和路径,如设置log_formataccess_logerror_log指令。

二、日志轮转

  • 工具选择:使用系统自带的logrotate工具,编辑/etc/logrotate.d/nginx配置文件,设置按天(daily)、保留天数(rotate)、压缩(compress)等参数,例如:
    /var/log/nginx/*.log {
        daily
        rotate 30
        compress
        delaycompress
        missingok
        create 0640 nginx nginx
        postrotate
            [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
        endscript
    }
    
    配置后通过logrotate -d /etc/logrotate.d/nginx测试,logrotate默认通过cron.daily每日自动执行。

三、实时监控

  • 命令行工具:使用tail -f实时查看日志,或multitail同时监控多个日志文件并高亮关键信息。
  • 图形化工具:通过GoAccess生成访问日志的实时分析报告,或使用ELK Stack(Elasticsearch+Logstash+Kibana)实现日志的可视化分析。

四、日志清理与备份

  • 自动清理:在logrotate配置中通过maxageminsize参数设置过期时间,或通过cron定时任务执行清理脚本,删除超过指定天数(如30天)的日志文件。
  • 备份策略:定期将重要日志归档至其他存储介质(如云存储),可通过scprsync实现异地备份。

五、安全与权限

  • 权限管理:确保日志目录权限为750,Nginx用户(如nginx)拥有写入权限,避免未授权访问。
  • 敏感信息过滤:在日志中避免记录敏感数据(如密码),可通过修改日志格式或使用日志过滤工具实现。

0