在Nginx日志文件名中包含日期

时间:2018-11-07 19:29:30

标签: nginx

我正在运行nginx 1.15.6,并且试图将当前日期包含在nginx日志文件名中。

类似这样的东西:access_log /var/log/nginx/access.2018.11.07.log main;

有人知道该怎么做吗?

3 个答案:

答案 0 :(得分:1)

server {

    if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})") {
        set $year $1;
        set $month $2;
        set $day $3;
    }

    access_log /var/log/nginx/$year-$month-$day-access.log;

答案 1 :(得分:1)

这是我最终使用的,并且效果很好:

map $time_iso8601 $year {
    default '0000';
    "~^(\d{4})-(\d{2})-(\d{2})" $1;
}
map $time_iso8601 $month {
    default '00';
    "~^(\d{4})-(\d{2})-(\d{2})" $2;
}
map $time_iso8601 $day {
    default '00';
    "~^(\d{4})-(\d{2})-(\d{2})" $3;
}

access_log  /var/log/nginx/access.$year-$month-$day.log  apm_json;

答案 2 :(得分:0)

在Nginx配置中,IF为Evil。有关原因的详细说明,请参见Nginx: If is Evil

更好的解决方案是使用地图记录日期。

以下示例。

map $time_iso8601 $year {
    default             'date';
    '~^(?<yyyy>\d{4})-'     $yyyy;
}
map $time_iso8601 $month {
    default             'not';
    '~^\d{4}-(?<mm>\d{2})-'     $mm;
}
map $time_iso8601 $day {
    default             'found';
    '~^\d{4}-\d{2}-(?<dd>\d{2})'    $dd;
}
map $time_iso8601 $logfile_date {
    default                         'date-not-found';
    '~^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})'    $year-$month-$day;
}

access_log c:/tools/nginx/logs/$logfile_date.access.log;