0

One of the things that I am investigating is using the dateext option for logrotate. However if I understood things correctly apache will keep writing to the files access.log and error.log.

I was wondering if there was a way to have apache log to a file access.log.YYYYMMDD and error.log.YYYYMMDD instead? Where YYYYMMDD would be the timestamp when the file was created.

Mohan Gulati
  • 211
  • 1
  • 2
  • 4

1 Answers1

1

Apache comes with rotatelogs which does exactly what you're looking for.

CustomLog "|/usr/bin/rotatelogs -l /var/logs/apache2/access.log.%Y%m%d 86400" combined
ErrorLog "|/usr/bin/rotatelogs -l /var/logs/apache2/error.log.%Y%m%d 86400"

Or you can write your own small script that does this. Apache than pipes it's log to that script's STDIN again using the following syntax

CustomLog |/path/to/logger.pl combined

Your script reads the log lines on STDIN and writes them to a logfile which name you can choose and change freely.

The script could look something like this

#!/usr/bin/perl
use warnings;
use strict;
use Time::Local;
use IO::Handle;

my $logfilePrefix = '/var/log/apache2/access.log.';
my $rotateAt;

openLog();

while(my $l = <STDIN>)
{
  reopenLog() if(time() >= $rotateAt);
  print LOG $l;
}

close(LOG);
exit 0;

sub openLog
{
  my ($day, $month, $year) = (localtime)[3,4,5];
  my $logfile = $logfilePrefix.sprintf("%04d%02d%02d", $year+1900, $month+1, $day);
  $rotateAt = timelocal(0, 0, 0, (localtime(time() + 86400))[3,4,5]);
  open(LOG, ">> $logfile") || die "couldn't write to $logfile: $!\n";
  LOG->autoflush(1);
}

sub reopenLog
{
  close(LOG);
  openLog();
}

Further reading: http://httpd.apache.org/docs/2.2/logs.html#piped

Lukas Loesche
  • 960
  • 1
  • 7
  • 11