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

xoshrz7s  于 2023-10-17  发布在  Nginx
关注(0)|答案(4)|浏览(139)

我正在运行nginx 1.15.6,我试图在nginx日志文件名中包含当前日期。
像这样的事情:access_log/var/log/nginx/access.2018.11.07.log main;
有人知道怎么做吗?

9rbhqvlz

9rbhqvlz1#

这就是我最终使用的,它工作得很好:

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;
oipij1gg

oipij1gg2#

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;
v2g6jxz6

v2g6jxz63#

如果是邪恶的,在Nginx配置。详细的说明可以在Nginx: If is Evil中找到。
更好的解决方案是使用Map记录日期。
示例如下。

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;
xoefb8l8

xoefb8l84#

我使用crontab每0 h 1 m运行一次shell脚本。

表单结构:

~/home/
    log/
        nginx/
            access/
                2023-10-03.log
                2023-10-02.log
                2023-10-01.log
                ...
            errors/
                2023-10-03.log
                2023-10-02.log
                2023-10-01.log
                ...

**概念:**创建一个带有日期的配置文件,然后将配置文件包含在域配置的服务器块中
/etc/nginx/conf.d中的域名配置

server {    
    listen 80;
    include /etc/nginx/log_by_date.conf;    
    root /.../;
...
}

Shell脚本update_log_by_date.sh

#! /bin/bash
date=$(date -Id)
home_folder="/home"
nginx_logs="$home_folder/logs/nginx"

# Create log folder if it does not exist
mkdir -p "$nginx_logs/access"
mkdir -p "$nginx_logs/errors"

# Create log file if does not exist
accessFile="$nginx_logs/access/${date}.log"
test -f $accessFile || touch $accessFile

errorFile="$nginx_logs/errors/${date}.log"
test -f $errorFile || touch $errorFile

# Set permission
chown -R nginx:nginx $nginx_logs

# Overwrite config
echo "access_log $nginx_logs/access/${date}.log;" > $home_folder/log_by_date.conf
echo "error_log $nginx_logs/errors/${date}.log warn;" >> $home_folder/log_by_date.conf

# Copy config file to nginx folder
sudo cp $home_folder/log_by_date.conf /etc/nginx

# Restart nginx to update config
sudo systemctl restart nginx

使用crontab每天以0 h1 m 1 0 * * * sh /folder/update_log_by_date.sh运行脚本

相关问题