Nginx日志管理大揭秘:logrotate工具与配置,日志按日期精准分割 ...

锦通  金牌会员 | 2024-3-27 17:13:09 | 来自手机 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 555|帖子 555|积分 1665

 
要让Nginx日志文件以日期为单位每天生成一个,你可以使用logrotate工具结合Nginx的配置。首先,确保你的系统上已经安装了logrotate。然后,按照下面的步骤修改Nginx的配置文件。
以下是一个简单的Nginx配置文件示例,假设Nginx版本为1.13.6。请注意,这只是一个基本示例,具体路径和配置可能需要根据你的实际情况进行调整。
  1. # Nginx配置文件路径:/etc/nginx/nginx.conf
  2. user nginx;
  3. worker_processes auto;
  4. error_log /var/log/nginx/error.log warn;
  5. pid /var/run/nginx.pid;
  6. events {
  7.     worker_connections 1024;
  8. }
  9. http {
  10.     log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  11.                       '$status $body_bytes_sent "$http_referer" '
  12.                       '"$http_user_agent" "$http_x_forwarded_for"';
  13.     access_log /var/log/nginx/access.log main;
  14.     sendfile on;
  15.     tcp_nopush on;
  16.     tcp_nodelay on;
  17.     keepalive_timeout 65;
  18.     types_hash_max_size 2048;
  19.     include /etc/nginx/mime.types;
  20.     default_type application/octet-stream;
  21.     server {
  22.         listen 80;
  23.         server_name localhost;
  24.         location / {
  25.             root /usr/share/nginx/html;
  26.             index index.html index.htm;
  27.         }
  28.         error_page 500 502 503 504 /50x.html;
  29.         location = /50x.html {
  30.             root /usr/share/nginx/html;
  31.         }
  32.     }
  33.     # 配置logrotate
  34.     # 创建一个新的logrotate配置文件,例如 /etc/logrotate.d/nginx
  35.     # 并添加以下内容:
  36.     logrotate /etc/logrotate.d/nginx {
  37.         daily
  38.         rotate 30
  39.         missingok
  40.         notifempty
  41.         dateext
  42.         dateformat -%Y%m%d
  43.         create 0640 nginx nginx
  44.         sharedscripts
  45.         postrotate
  46.             [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
  47.         endscript
  48.     }
  49. }
复制代码
在上述配置中,关键的logrotate配置位于/etc/logrotate.d/nginx文件中。这个配置指定了每天轮转一次日志文件,保留30天的日志文件,以日期格式命名日志文件,并在轮转后使用kill -USR1命令通知Nginx重新打开日志文件,以便新的日志可以写入。
确保在修改配置文件后测试Nginx配置是否正确,然后重新加载Nginx以使更改生效。
 



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

锦通

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表