Apache log rotation windows

Как в Apache под Windows настроить автоматическую ротацию и очистку логов

В данной статье мы рассмотрим как установить и настроить плагин mod_log_rotate, который служит для ротации логов на рабочем сервере.

С помощью этого плагина мы сможем в Apache в 2.4 под Windows настроить автоматическую чистку логов со временем.

Файл данного плагина не входит в стандартный набор Apache, но команда apachelounge компилирует его для Windows. Перейдите на сайт https://www.apachelounge.com/download/, найдите и скачайте файл mod_log_rotate:

Распакуйте архив и поместите файл mod_log_rotate.so в папку modules, если вы устанавливали по этой инструкции, то это папка C:\Server\bin\Apache24\modules\.

Для включения этого модуля, добавьте в ваш конфигурационный файл httpd.conf (C:\Server\bin\Apache24\conf\httpd.conf) строки:

Чтобы изменения вступали в силу, не забывайте при каждом изменении конфигурационного файла httpd.conf перезапускать веб-сервер!

Интервал ротации логов по умолчанию установлен на 86400 секунд (это один день). С помощью директивы

можно установить другой интервал ротации в секундах. Самый короткий интервал, который может быть установлен, равен 60 секундам.

Обычно интервал ротации журнала основан на UTC. Например, интервал 86400 (один день) приведёт к ротации журналов в UTC 00:00.

С помощью следующей директивы вы можете сделать так, чтобы ротация журналов происходила по местному времени:

У директивы RotateInterval может быть альтернативная опция:

Она указывает смещение времени ротации журналов веб сервера. Например:

приведёт к тому, что логи будут ротироваться в 23:00 UTC.

Теперь в качестве имени для настраиваемого лога можно указать дату в формате strftime(). К примеру вы можете сделать что-то вроде такого:

И в результате у вас будут логи с понятным для человека датой и временем создания.

Внимание

После включения mod_log_rotate, этот модуль отвечает за весь вывода журнала веб сервера, даже если впоследствии используется RotateLogs Off.

Это означает, что директива BufferedLogs, которая реализуется mod_log_config, будет игнорироваться.

Поскольку BufferedLogs не документирована и помечена как экспериментальная функция, это не должно быть проблемой в производственных средах.

Альтернатива для rotatelogs

Использование модуля mod_log_rotate является альтернативой для поставляемой с Apache программы rotatelogs. Если вы не хотите устанавливать дополнительный модуль, то используйте rotatelogs (документация). Если вам нужна инструкция по rotatelogs, то пишите в комментариях!

Связанные статьи:

  • Удалённый просмотр и поиск по логам Apache в Windows (модуль mod_view) (100%)
  • Почему в логах ошибок Apache не сохраняются записи об ошибке 404 (83.4%)
  • Apache log (логи): как настроить и анализировать журналы веб-сервера (77.5%)
  • Как ограничить пропускную способность Apache на Windows для IP и отдельных файлов (75.1%)
  • Модуль Apache mod_alias (75.1%)
  • Как установить ownCloud сервер в Windows (RANDOM — 50%)

Comments

Спасибо. mod_log_rotate затрагивает как и access.log так и error.log?

Нет, с логом ошибок этот модуль не работает. Если интересно почему: ошибки могут быть такими, что аварийно завершится процесс сервера, по этой причине, например, ошибки не буферизируются (выводятся сразу). По этой причине в Linux различают «стандартный вывод» и «стандартный вывод ошибок» — оба выводятся в консоль, но второй также не буферизируется. То есть ошибки выводятся сразу как только возникли, не надеясь, что процесс Apache, а уж тем более какой-то модуль, переживут эту ошибку.

Тем не менее с использованием внешней программы можно управлять и журналом ошибок (если Apache вылетит, внешняя программа всё равно обработает полученную информацию). В частности это умеет упомянутая в инструкции программа rotatelogs (в Windows это rotatelogs.exe).

Я подготовлю инструкцию по rotatelogs и покажу как можно ротировать логи ошибок.

Спасибо буду крайне признателен за Вашу инструкцию по rotatelogs

Admin’s Notes

воскресенье, 17 апреля 2016 г.

Подключаем (включаем) ротацию log файлов на Apache x64 2.4.20 под Windows Server 2008

Тут опишу два способа ротации логов.

Читайте также:  Displaylink driver windows 10

СПОСОБ РАЗ

2) Копируем из архива файл mod_log_rotate.so в каталог с модулями Apache (обычно это подкаталог modules)

3) В файл httpd.conf добавляем строку LoadModule log_rotate_module modules/mod_log_rotate.so

4) В файл httpd.conf добавляем строку RotateLogs On

5) В файл httpd.conf добавляем строку RotateLogsLocalTime On

6) По желанию добавляем в файл httpd.conf добавляем строку RotateInterval указываем значение в секундах через которое будут создаваться новые файлы логов. По умолчанию используется значение 86400 то есть один день. Если эту строчку не указать, то будет использовано значение по умолчанию. Минимальное значение 60 секунд.

7) В файле httpd.conf изменяем строку создания файла логов доступа. Например на такую: «E:/iLogs/access %Y.%m.%d %B %H-%M-%S.log» combinedio

То же самое проделываете для всех ваших логов доступа (access.log) на виртуальных хостингах. Иначе к их названию просто прилепиться случайное число.

8) Перезапускаем Apache

P.S. mod_log_rotate 1.00a for Apache 2.4 Win64 VC14 работает только для логов доступа. Для логов ошибок он не работает.

СПОСОБ ДВА

При помощи утилиты – rotatelogs.

Rotatelogs — небольшая утилита в составе APACHE, позволяющая осуществлять ротацию логов по времени и по размеру.

rotatelogs [ -l ] [ -f ] logfile rotationtime|filesizeM [ offset ]

-l — Использовать локальное время

-f — Открыть новый файл немедленно, не дожидаясь добавления в него записи

logfile — путь и базовое название лога. Допускается использование модификаторов имени файла (ниже)

rotationtime — время ротации в секундах

filesizeM — максимальный размер лога в мегабайтах

offset — смещение во времени в минтах

Примеры для APACHE под WINDOWS

Внимание. надо указывать либо полный путь к утилите rotatelogs либо отностительный, а так же файлу логов.

CustomLog «|C:/bin/rotatelogs.exe C:/var/logs/logfile 86400″ common

CustomLog «|bin/rotatelogs.exe -l C:/var/logs/logfile.%Y.%m.%d 86400″ common

CustomLog «|C:/bin/rotatelogs.exe C:/var/logs/logfile 5M» common

ErrorLog «|C:/bin/rotatelogs.exe C:/var/logs/errorlog.%Y-%m-%d-%H_%M_%S 5M»

Модификаторы названия файла

%A full weekday name (localized)

%a 3-character weekday name (localized)

%B full month name (localized)

%b 3-character month name (localized)

%c date and time (localized)

%d 2-digit day of month

%H 2-digit hour (24 hour clock)

%I 2-digit hour (12 hour clock)

%j 3-digit day of year

%M 2-digit minute

%p am/pm of 12 hour clock (localized)

%S 2-digit second

%U 2-digit week of year (Sunday first day of week)

%W 2-digit week of year (Monday first day of week)

%w 1-digit weekday (Sunday first day of week)

%X time (localized)

%x date (localized)

%Z time zone name

Вторым способом можно ротировать и логи ошибок. Но он не позволить использовать пробелы между модификаторами.

Можно одновременно использовать оба метода. Например первый для логов доступа, а второй для лога ошибок.

Либо же только второй для обоих логов.

Возможно в будущем, первым способом можно будет ротировать и логи ошибок.

by Peter Lorenzen

The Apache HTTP Server does not rotate log files.

On Red Hat Linux, Oracle Linux etc. rotation of the Apache log files are handled by cron.daily and logrotate.

On Windows it is a bit more difficult because of the way open files are locked. You have two options, either stop Apache and do the rotate yourself or use an Apache feature called Piped Logs.

Instead of writing to log files Apache can write to a pipe. Another program can then read from the pipe and handle the logging.

The Apache HTTP Server includes a rotatelogs executable that can be used.

Below are some examples of how you use piped logs and rotatelogs.

This will result in log files named like this:
error.2013.08.15.log
access.2013.08.15.log
ssl_access.2013.08.15.log
ssl_request.2013.08.15.log

A new log file will be created every 24 hours.

Now all you have to do is to find a way to delete old log files.

Читайте также:  Intel hd graphics 610 драйвер windows 32 bit

I am no PowerShell expert but this get the job done.

While you test you can use the -WhatIf parameter. It will tell you which files will be deleted but it will not delete anything:

Hi Peter
thanks for sharing this….I have been running all around for this and finally found it here….But its not working me, please suggest, I have all 3 ways but still get an error message while starting apache “>>> ErrorLog takes one argument, The filename of the error log” in windows event log.

I tried all these but no luck..
ErrorLog “|bin/rotatelogs.exe -l “C:/Program Files/CollabNet/Subversion Server/httpd/logs/error.%Y.%m.%d.log” 86400″ common

ErrorLog “|bin/rotatelogs.exe -l C:/Program Files/CollabNet/Subversion Server/httpd/logs/error.%Y.%m.%d.log” 86400 common

ErrorLog “C:\Program Files\CollabNet\Subversion Server\httpd\bin\rotatelogs.exe -l C:/Program Files/CollabNet/Subversion Server/httpd/logs/error.%Y.%m.%d.log” 86400 common

Hi,
You use:
ErrorLog “|bin/rotatelogs.exe -l “C:/Program Files/CollabNet/Subversion Server/httpd/logs/error.%Y.%m.%d.log” 86400″ common
It should be:
ErrorLog “|bin/rotatelogs.exe -l C:/Program Files/CollabNet/Subversion Server/httpd/logs/error.%Y.%m.%d.log 86400” common

But this will probably still not work because there is a space in the path. You can create symlink and use that instead.
For example:
C:/Program Files/CollabNet
mklink /d SubversionServer “Subversion Server”

thanks Peter for such a quick response…
does that mean i need to create symlink for Program Files aswell, Let me try and will update you..

Yes sorry did not notice there were two spaces in the path.

You made my day Peter.. created one symlink as suggested by you and works now…..I hope my log rotation works now…thanks once again…wish you all the best

just an update ..for symlink i tried mutiple commands …but this one worked
mklink /D SubversionServer “c:Subversion Server”

First of all thanks, I too was searching for this for ages.

I had the same issue as Gill with spaces in the path and by trial and error managed to get it to work by just enclosing the path in single quotes, so using Gill’s path it would be :-

ErrorLog “|bin/rotatelogs.exe -l ‘C:/Program Files/CollabNet/Subversion Server/httpd/logs/error.%Y.%m.%d.log’ 86400″ common

I have implemented log rotation in Windows server 2003 R2 as shown below, but it is not working.
CustomLog “| E:/apache/bin/rotatelogs.exe -l E:/apache/logs/access.%Y.%m.%d.log 86400” combined
ErrorLog “|E:/apache/bin/rotatelogs.exe -l E:/apache/logs/error.%Y.%m.%d.log 86400”

Could you please help.

Thanks in advance.

It looks like you are using the wrong quotes character. You should use » not “ or ”. But it might just be a copy/past or display error 🙂
Regards Peter

Dear Peter,
Thank you for your prompt response.
I was trying with the correct quotes as below:
ErrorLog “|E:/apache/bin/rotatelogs.exe -l E:/apache/logs/error.%Y.%m.%d.log 86400”.
I dint do copy/paste.
Please suggest me any other possible errors
could you please clarify me that, whether we can implement rotate logs function independent of the version of apache .
Requesting your kind help to troubleshoot the issue.

I have only used this for version 2.2.20 and above. Which error do you get? Can you see anything in the error log? Can you see anything in the Windows Event log?

Apologies for late reply.
I checked event log and error log , i dont see any errors.
Firstly the logs are not updating if i edit the the httpd.conf file as below.
As shown below, in server1 and server2 the rotation has been completed, but in server3 and 4 it is not done.
Kindly help
==================================================
server1
D:\wamp\bin\apache\Apache2.2.11\conf

ErrorLog “|bin/rotatelogs.exe -l E:/wamp/logs/apache_error.log.%Y.%m.%d.log 86400”

#CustomLog “e:/wamp/logs/access.log” common

CustomLog “|bin/rotatelogs.exe -l E:/wamp/logs/apache_access.log.%Y.%m.%d.log 86400” common

ErrorLog “|bin/rotatelogs.exe -l D:/wamp/logs/apache_error.log.%Y.%m.%d.log 86400”

CustomLog “|bin/rotatelogs.exe -l D:/wamp/logs/apache_access.log.%Y.%m.%d.log 86400” common
======================================================
server3
E:\Apache\conf

ErrorLog “|bin/rotatelogs.exe -l E:/Apache/logs/apache_error.log.%Y.%m.%d.log 86400”

CustomLog “|bin/rotatelogs.exe -l E:/Apache/logs/apache_access.log.%Y.%m.%d.log 86400” common
========================================
server4

ErrorLog “|bin/rotatelogs.exe -l E:/apache/logs/apache_error.log.%Y.%m.%d.log 86400”

CustomLog “|bin/rotatelogs.exe -l E:/apache/logs/apache_access.log.%Y.%m.%d.log 86400” common
==============================

Do you know why i have a cmd.exe window opening when i use rotatelogs for access ??
Can’t close it.
Thanks for response.

Читайте также:  Драйвер для samsung n130 windows

I don’t know. I can see others have had the same problem but I have not found any solution.
Regards Peter

The only idea I have is to input the full path to the rotatelogs.exe, to see if that makes a difference.
Regards Peter

I have tried even with full path to the rotatelogs.exe, but that doesnt work out.
K, fine..Thank you peter.

Could this work? To overwrite weekly and limit the growth?

CustomLog “|bin/rotatelogs.exe -l logs/access.%A.log 15M” common

Sorry Tilo I have never tried that. I do not work much on Windows and I have only tried what I put in the post 🙂
Regards Peter

I think this tool can really be useful to delete log or obsolete files from your servers:
https://sourceforge.net/projects/autodeletions/

Thanks for the tip Alberto

can you help me with aapche server log file for 2-3 months, i need it for my research..
thanx in advance
lucky

Really appreciate what you shared, very helpful, but there’s an odd issue for me now. The logs are rotating every 24 hours, but the start and end time in the logs are 10:00:00 AM and 9.59.59 AM respectively. This does not even match with the time when apache services were restarted for the change to come into effect (around 2AM). Any suggestions?

Well just explored a bit further and found -l missing in my command 🙂 -l uses local time rather than GMT.

CustomLog “|bin/rotatelogs -l /var/logs/logfile.%Y.%m.%d 86400” common

I have configured the log rotation as below
#CustomLog logs/access.log common
CustomLog “|bin/rotatelogs.exe -l logs/access.%Y.%m.%d.log 86400” common

But the logs are rotated by the oldest date with the filename ‘access.log’ and recent log as eg: access.2014.06.24.log (of today) but i think it should the opposite.

Need assistance please

Hi Abdul,
The access.log file is the original file and should be ignored.
Regards Peter

Thanks for posting wonderful info.

ErrorLog “|bin/rotatelogs.exe -l D:/Dev/Apache2.2/logs/error.%Y.%m.%d.%H_%M_%S.log 60”

Not sure why but Custom log is not working.

CustomLog “|bin/rotatelogs.exe -l D:/Dev/Apache2.2/logs/access.%Y.%m.%d.%H_%M_%S.log 60” common

Even though my access.log file is of 8 MB.

Once I update the httpd.conf then I do restart my Apache Services after that I do that Error.log file gets updated but it doesn’t create the access.log file.

But when I put below entry alone.

ErrorLog “|bin/rotatelogs.exe -l D:/Dev/Apache2.2/logs/access.%Y.%m.%d.%H_%M_%S.log 60” it creates the access.log file with timestamp.

Could you please help me to setup this.

Thanks in advance.

Hi Vikram,
I think the access log is first created when there is a request to the server.
Regards Peter

Hi Peter,
Thank for the tutorial. Every thing is working fine. I made it to work in two servers and in my local PC.
But, I had a issue when tried for the next time.
Once configuring httpd.conf, Apache does creates rotated log files for both access.log and error.log after restarting, but it does not creates anymore log in the actual error.log file, whereas the logs is updated in the rotated log file.
Only after removing rotate log command for Error Log from httpd.conf, again it works fine as usual.
Please Help.

[Do you know why i have a cmd.exe window opening when i use rotatelogs for access ??
Can’t close it.
Thanks for response.

Hi I had the same problem in a Windows 2003 r2, I found a property in the service Apache 2.2. If you use the local system account to run the service, check if you have a tick in “Allow service to interact with desktop”, uncheck this option. Works in my case.

P.d: Sorry for my english 😛

Works Great, thanks

Thank you for sharing – everything in one place – saved my day. Thumbs up!

Thanks for your precious informations about logrotate under Windows 🙂

Оцените статью