隐藏

按天保存nginx日志

发布:2022/12/12 9:53:32作者:管理员 来源:本站 浏览次数:622

修改前


log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '

                     '$status $body_bytes_sent "$http_referer" '

                     '"$http_user_agent" "$http_x_forwarded_for"';


修改后(将$ time_local改成$ time_iso8601)


 log_format  main  '$remote_addr - $remote_user [$time_iso8601] "$request" '

                     '$status $body_bytes_sent "$http_referer" '

                     '"$http_user_agent" "$http_x_forwarded_for"';


然后在server 中添加以下代码


 if ($time_iso8601 ~ '(\d{4}-\d{2}-\d{2})') {

               set $time $1;

 }

 access_log  logs/$time.access.log  main;


完整配置(参考)


user  root;

worker_processes  1;


#error_log  logs/error.log;

#error_log  logs/error.log  notice;

error_log  logs/error.log  debug;


#pid        logs/nginx.pid;



events {

   worker_connections  1024;

}



http {

   include       mime.types;

   default_type  application/octet-stream;


   log_format  main  '$remote_addr - $remote_user [$time_iso8601] "$request" '

                     '$status $body_bytes_sent "$http_referer" '

                     '"$http_user_agent" "$http_x_forwarded_for"';


   #access_log  logs/$tttt.access.log  main;


   access_log  logs/access.log  main;


   sendfile        on;

   #tcp_nopush     on;


   #keepalive_timeout  0;

   keepalive_timeout  65;


   #gzip  on;

 

   upstream testTomcat{

       server 192.168.175.170:8880 weight=1;

       server 192.168.175.171:8880 weight=1;

   }

 

   server {

       listen       8888;

       server_name  localhost;


       #charset koi8-r;


      if ($time_iso8601 ~ '(\d{4}-\d{2}-\d{2})') {

               set $time $1;

       }

       access_log  logs/$time.access.log  main;

       #access_log  logs/host.access.log  main;


       location / {

           #root   html;

           #index  index.html index.htm;#root   html;

           index  index.html index.htm;

           proxy_pass http://testTomcat/ssm/;

       }

   }

}


修改完保存退出,重启nginx 命令:./nginx -s reload


如果error.log出现报错


2020/04/28 22:47:55 [crit] 7727#0: *32 open() "/usr/local/nginx/logs/2020-04-28.access.log" failed (13: Permission denied) while logging request, client: 192.168.175.1, server: localhost, request: "GET / HTTP/1.1", upstream: "http://192.168.175.171:8880/ssm/", host: "192.168.175.170:8888"


这是因为当前用户没有权限open() “/usr/local/nginx/logs/2020-04-28.access.log” 可以chown重新执行拥有者。


我这里文件的拥有者为root 所以nginx.conf配置文件中设置成 user root;也可以