> Linux服务器 > nginx >

nginx 在配置文件中设置日志按年、月、日分割

需要使用到 [Math Processing Error]time_iso8601 内嵌变量来获取时间。time_iso8601内嵌变量来获取时间。time_iso8601格式如下:2018-09-21T16:01:02+02:00。然后使用正则表达式来获取所需时间的数据。

按天分割日志
配置在server段:

if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})") {
        set $year $1;
        set $month $2;
        set $day $3;
}
access_log  /var/logs/xxxx/access/xxxxx_xx_access_$year-$month-$day.log  main;

查看日志是否生成:

[xx@xxx access]# ll  xxxxx_xx_access_2018-09-21.log
-rw-r--r-- 1 root root 408848 Sep 21 16:01 xxxxx_xx_access_2018-09-21.log

按小时、分、秒分割:

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;
}
access_log  /var/logs/xxxx/access/xxxxx_xx_access_$year-$month-$day-hour-minutes-seconds.log  main;

在必要的时候可以按小时分割,方便日志分析。

(责任编辑:IT)