学而实习之 不亦乐乎

Nginx 日志时间格式设置

2023-10-23 21:18:43

Nginx log日志是我们大数据分析的重要文件,其中有个时间戳字段,Nginx本身再带了两种类型:

  1. $time_local
  2. $time_iso8601

展示样式基本为:"04/Sep/2020:18:22:03 +0800" 这种类型,打开日志查看记录时很不方便,所以最好格式化为 YYYY-MM-DD hh:ss:mm 这样看的比较舒服

1、自定义时间变量

首先在nginx.conf中的每个server下自定义时间变量

# 自定义时间变量
if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})") {
    set $year $1;
    set $month $2;
    set $day $3;
    set $hour $4;
    set $minutes $5;
    set $seconds $6;
}

2、定义log_fomart格式

log_format  mylog   '{"timestamp": "$year$month$day $hour:$minutes:$seconds",'
                '"host": "$remote_addr",'
                '"client_id": "$remote_user",'
                '"request": "$request",'
                '"agent": "$http_user_agent"}';

3、测试

重启测试后发现无效,然后我们继续调整,上面方便大概率是行不通了,我们重新来调整我们的原则是不修改 nginx 源代码的,以便平滑升级 nginx,所以我们选择第二种方法,具体如下:

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '"$remote_addr" "$fmt_localtime" "$request_id" "$requ
                      '"$status" "$body_bytes_sent" "$request_length" "$htt
                      '"$http_user_agent" "$http_x_forwarded_for" "$http_ho

    #access_log  /data/log/nginx/access.log  main;   

    map $host $fmt_localtime {
        default '';
    }

    log_by_lua_block {
       ngx.var.fmt_localtime = ngx.localtime();
    }
  ...  
}

1) 首先我们自定了一个nginx 变量 $fmt_localtime,因为在http context不能够使用 set $variable。

所以我们采用map的方式如下:

map $host $fmt_localtime {
    default '';
}

2) 然后我们用 log_by_lua_block 设置 ngx.fmt_localtime 的时间