Nginx 日志按天生成

Nginx About 1,912 words

说明

无需借助logrotate等日志处理工具。

配置

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    map $time_iso8601 $logdate {
        '~^(?<ymd>\d{4}-\d{2}-\d{2})' $ymd;
        default                       'date-not-found';
    }

    access_log /var/log/nginx/access-$logdate.log main;
    open_log_file_cache max=10;
}

或者:

if不能用在http作用域中。

log_format  main  '$remote_addr - $remote_user [$time_local] "$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 $year $1;
        set $month $2;
        set $day $3;
    }
    access_log /var/log/nginx/access-$year-$month-$day.log main;
    open_log_file_cache max=10;
}

open_log_file_cache

每一条日志记录的写入都是先打开文件再写入记录,然后关闭日志文件。如果日志文件路径中使用了变量为提高性能,可以使用open_log_file_cache指令设置日志文件描述符的缓存。

语法

open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];
  • max:设置缓存中描述符的最大数量;如果缓存被占满,最近最少使用(LRU)的描述符将被关闭。
  • inactive:设置缓存文件描述符在多长时间内没有被访问就关闭; 默认为10秒。
  • min_uses:设置在inactive参数指定的时间里, 最少访问多少次才能使文件描述符保留在缓存中;默认为1
  • valid:设置一段用于检查超时后文件是否仍以同样名字存在的时间; 默认为60秒。
  • off:禁用缓存。
  • 默认值:open_log_file_cache off
  • 作用域:http, server, location

注意

error.log出现错误日志:testing "/etc/nginx/html" existence failed (2: No such file or directory) while logging request

2019/07/26 15:24:37 [error] 43157#43157: *52454578 testing "/etc/nginx/html" existence failed (2: No such file or directory) while logging request, client: xxx.xx.xxx.xxx, server: , request: "POST /a/b/c HTTP/1.1", upstream: "http://xxxxx", host: "xxx.com"

解决办法

  • 方法一:作用域下添加root /var/www(或其他已经存在的路径)
  • 方法二(推荐):创建/etc/nginx/html文件夹(Nginx安装目录下html文件夹,可能不一定安装在/etc/nginx下)

重新加载

nginx -s reload
Views: 9,802 · Posted: 2019-07-22

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh