Nginx – Log rotation on NginX in Configuration file

loggingnginx

I've tried this tutorial to rotate log file without external software, but it seems it doesn't work, my configuration on the server { block:

if ($time_iso8601 ~ "^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})") {}
access_log /var/log/access-$year-$month-$day.log;
error_log /var/log/error-$year-$month-$day.log;

and the file created, named:

-rw-r--r-- 1 root root    0 May 28 17:46 error-$year-$month-$day.log

my NginX version:

nginx version: nginx/1.8.0

built with OpenSSL 1.0.2a 19 Mar 2015

TLS SNI support enabled

configure arguments: –prefix=/etc/nginx –conf-path=/etc/nginx/nginx.conf –sbin-path=/usr/bin/nginx –pid-path=/run/nginx.pid –lock-path=/run/lock/nginx.lock –user=http –group=http –http-log-path=/var/log/nginx/access.log –error-log-path=stderr –http-client-body-temp-path=/var/lib/nginx/client-body –http-proxy-temp-path=/var/lib/nginx/proxy –http-fastcgi-temp-path=/var/lib/nginx/fastcgi –http-scgi-temp-path=/var/lib/nginx/scgi –http-uwsgi-temp-path=/var/lib/nginx/uwsgi –with-imap –with-imap_ssl_module –with-ipv6 –with-pcre-jit –with-file-aio –with-http_dav_module –with-http_gunzip_module –with-http_gzip_static_module –with-http_realip_module –with-http_spdy_module –with-http_ssl_module –with-http_stub_status_module –with-http_addition_module –with-http_degradation_module –with-http_flv_module –with-http_mp4_module –with-http_secure_link_module –with-http_sub_module

Best Answer

See my comment above, and cpburnz's reasoning, but if you really want to proceed:

You could write a script which writes just the log commands to an include file, with the current date hard-coded. You'd have that included into your nginx config file, and your script would restart or reload nginx after writing the log commands to the include file.

Something like:

#!/bin/bash

date=`date -Id`

cat > /etc/nginx/includes/log_by_date.inc <<EOF
access_log /var/log/access-${date}.log;
error_log /var/log/error-${date}.log;
EOF

/etc/init.d/nginx restart

You'd run that from cron, most likely close to midnight.

plus of course you need to include /etc/nginx/includes/log_by_date.inc where you have your current logging commands.