Restart logrotate in linux

Ротация логов в Linux и FreeBSD с помощью logrotate

С помощью утилиты logrotate можно настроить автоматическое удаление (чистку) лог-файлов. В противном случае, некоторые логи могут заполнить все дисковое пространство, что приведет к проблемам в работе операционной системы.

Установка

Чаще всего, в Linux данная утилита установлена по умолчанию. Если это не так, установка выполняется следующими командами.

Ubuntu / Debian:

apt-get install logrotate

CentOS / Red Hat:

yum install logrotate

FreeBSD:

pkg install logrotate

Утилита не работает как служба, поэтому нет необходимости в ее запуске или перезагрузке (logrotate start или logrotate restart делать не нужно).

Настройка

Для приложение, ротация логов настраивается в отдельных файлах, расположенных по пути /etc/logrotate.d/ (во FreeBSD — /usr/local/etc/logrotate.d/).

К примеру, нам необходимо настроить ротацию лога для logstash-forwarder. Создаем файл со следующим содержимым:

/var/log/logstash-forwarder/* <
rotate 30
size=10M
missingok
notifempty
daily
compress
delaycompress
maxage 30
create 0644 root root
postrotate
/usr/bin/systemctl restart logstash-forwarder
endscript
>

  • rotate 30 — хранить последние 30 ротированных файлов. Остальные удалять.
  • size=10M — пока размер лог-файла не превысит 10 мегабайт, он не будет ротироваться.
  • missingok — если файла не существует, не выкидывать ошибку.
  • notifempty — если файл пустой, не выполнять никаких действий.
  • daily — делать ротацию каждый день.
  • compress — сжимать ротированные файлы.
  • delaycompress — сжимать только предыдущий журнал. Позволяет избежать ошибок, связанных с отсутствием доступа к используемому файлу.
  • maxage 30 — хранить ротированные файлы за последние 30 дней. Остальные удалять.
  • create 0644 root root — создать новый лог-файл после ротирования.
  • postrotate . endscript — скрипт, который необходимо выполнить после чистки лога.

* /var/log/logstash-forwarder/* — путь к файлу, который нужно ротировать. * указывает, что нужно чистить все файлы, которые расположены в каталоге /var/log/logstash-forwarder.
* напомню, что во FreeBSD, путь будет /usr/local/etc/logrotate.d/logstash.

При настройке необходимо проверять работу сервиса после ротации лога. Некоторые службы могут перестать работать без лог-файла. В данном случае, необходимо создавать новый (create). Также, в некоторых случаях, сервис необходимо перезапускать, так как при создании нового файла меняется его дескриптор.

Запуск вручную

Запуск выполняется со следующим синтаксисом:

logrotate -f /etc/logrotate.d/logstash

Автоматический запуск

Задание на автоматический запуск создается по умолчанию в файле /etc/cron.daily/logrotate. Если изучить его содержимое, мы увидим, что идет запуск logrotate, который читает все файлы в директории /etc/logrotate.d/ и выполняющий для каждого из них ротацию.

Если для какого-то приложения необходимо выполнять ротацию лога по особому расписанию, узнаем полный путь до утилиты logrotate:

* в моем случае, это было /usr/sbin/logrotate.

Получив путь, создаем правило в cron:

0 0 * * * /usr/sbin/logrotate -f /etc/logrotate.d/logstash

* в данном примере в 00:00 будет запускаться logrotate и чистить логи с нашей настройкой для logstash-forwarder.

Источник

How to Setup and Manage Log Rotation Using Logrotate in Linux

One of the most interesting (and perhaps one of the most important as well) directories in a Linux system is /var/log . According to the Filesystem Hierarchy Standard, the activity of most services running in the system are written to a file inside this directory or one of its subdirectories.

Such files are known as logs and are the key to examining how the system is operating (and how it has behaved in the past). Logs are also the first source of information where administrators and engineers look while troubleshooting.

If we look at the contents of /var/log on a CentOS/RHEL/Fedora and Debian/Ubuntu (for variety) we will see the following log files and subdirectories.

Please note that the result may be somewhat different in your case depending on the services running on your system(s) and the time they have been running.

Читайте также:  Linux как установить все пакеты

In RHEL/CentOS and Fedora

In Debian and Ubuntu

In both cases, we can observe that some of the log names end as expected in “log”, while others are either renamed using a date (for example, maillog-20160822 on CentOS) or compressed (consider auth.log.2.gz and mysql.log.1.gz on Debian).

This is not a default behavior based on the chosen distribution but can be changed at will using directives in the configuration files, as we will see in this article.

If logs were kept forever, they would eventually end up filling the filesystem where /var/log resides. In order to prevent that, the system administrator can use a nice utility called logrotate to clean up the logs on a periodic basis.

In a few words, logrotate will rename or compress the main log when a condition is met (more about that in a minute) so that the next event is recorded on an empty file.

In addition, it will remove “old” log files and will keep the most recent ones. Of course, we get to decide what “old” means and how often we want logrotate to clean up the logs for us.

Installing Logrotate in Linux

To install logrotate, just use your package manager:

It is worth and well to note that the configuration file ( /etc/logrotate.conf ) may indicate that other, more specific settings may be placed on individual .conf files inside /etc/logrotate.d.

This will be the case if and only if the following line exists and is not commented out:

We will stick with this approach, as it will help us to keep things in order, and use the Debian box for the following examples.

Configure Logrotate in Linux

Being a very versatile tool, logrotate provides plenty of directives to help us configure when and how the logs will be rotated, and what should happen right afterward.

Let’s insert the following contents in /etc/logrotate.d/apache2.conf (note that most likely you will have to create that file) and examine each line to indicate its purpose:

The first line indicates that the directives inside the block apply to all logs inside /var/log/apache2:

  • weekly means that the tool will attempt to rotate the logs on a weekly basis. Other possible values are daily and monthly.
  • rotate 3 indicates that only 3 rotated logs should be kept. Thus, the oldest file will be removed on the fourth subsequent run.
  • size=10M sets the minimum size for the rotation to take place to 10M. In other words, each log will not be rotated until it reaches 10MB.
  • compress and delaycompress are used to tell that all rotated logs, with the exception of the most recent one, should be compressed.

Let’s execute a dry-run to see what logrotate would do if it was actually executed now. Use the -d option followed by the configuration file (you can actually run logrotate by omitting this option):

The results are shown below:

Rotate Apache Logs with Logrotate

Instead of compressing the logs, we could rename them after the date when they were rotated. To do that, we will use the dateext directive. If our date format is other than the default yyyymmdd, we can specify it using dateformat.

Note that we can even prevent the rotation from happening if the log is empty with notifempty. In addition, let’s tell logrotate to mail the rotated log to the system administrator ([email protected] in this case) for his / her reference (this will require a mail server to be set up, which is out of the scope of this article).

If you want to get emails about logrotate, you can setup Postfix mail server as shown here: Install Postfix Mail Server

This time we will use /etc/logrotate.d/squid.conf to only rotate /var/log/squid/access.log:

As we can see in the image below, this log did not need to be rotated. However, when the size condition is met (size=1M), the rotated log will be renamed access.log-25082020 (if the log was rotated on August 25, 2020) and the main log (access.log) will be re-created with access permissions set to 0644 and with root as owner and group owner.

Читайте также:  Microsoft 365 e5 developer without windows and audio conferencing

Finally, when the number of logs finally reaches 6, the oldest log will be mailed to [email protected].

Rotate Squid Logs with Logrotate

Now let’s suppose you want to run a custom command when the rotation takes place. To do that, place the line with such command between the postrotate and endscript directives.

For example, let’s suppose we want to send an email to root when any of the logs inside /var/log/myservice gets rotated. Let’s add the lines in red to /etc/logrotate.d/squid.conf:

Last, but not least, it is important to note that options present in /etc/logrotate.d/*.conf override those in the main configuration file in case of conflicts.

Logrotate and Cron

By default, the installation of logrotate creates a crontab file inside /etc/cron.daily named logrotate. As it is the case with the other crontab files inside this directory, it will be executed daily starting at 6:25 am if anacron is not installed.

Otherwise, the execution will begin around 7:35 am. To verify, watch for the line containing cron.daily in either /etc/crontab or /etc/anacrontab.

Summary

In a system that generates several logs, the administration of such files can be greatly simplified using logrotate. As we have explained in this article, it will automatically rotate, compress, remove, and mail logs on a periodic basis or when the file reaches a given size.

Just make sure it is set to run as a cron job and logrotate will make things much easier for you. For more details, refer to the man page.

Do you have any questions or suggestions about this article? Feel free to let us know using the comment form below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Настройка Logrotate

В Linux, большинство сервисов и программ, которые работают в фоне, таких как Apache, Nginx, Postfix и других записывают информацию о своем состоянии, результатах работы и ошибках в лог файлы. Стандартное расположение логов или как их еще называют — журналов — в папке /var/log.

С помощью анализа логов вы можете понять что работает не так, почему произошла ошибка и как решить возникшую проблему. Но тот кроется одна проблема. Размер логов постоянно растет и они занимают все больше и больше места на диске, поэтому необходимо вовремя чистить логи и удалять устаревшие записи, чтобы они не мешали нормально работать. Это можно делать вручную время от времени или настроить скрипты Cron, но есть еще более простой вариант — утилита logrotate. В этой статье будет рассмотрена настройка logrotate и ее использование.

Как работает Logrotate?

Утилита Logrotate предназначена для автоматизации обработки журналов. Она может выполнять с ними необходимые действия в зависимости от определенных условий и правил соответствия. Например, можно сжимать журналы в архив или отправлять на другой сервер когда они достигают определенного размера, возраста, или других параметров.

Проверку условий можно настроить ежедневно, еженедельно или ежемесячно. Это позволяет создать схему ротации логов, удобную именно для вас и вашего сервера. Также ротация логов может быть полезна на домашнем компьютере, но здесь она не так важна как на серверах, где только в логи Apache могут записываться до сотен тысяч строк ежедневно.

Читайте также:  Сбросить пароль линукс ubuntu

Настройка Logrotate

Logrotate — это популярная утилита, поэтому в большинстве дистрибутивов она поставляется по умолчанию. Вы можете убедиться, что программа установлена в вашем дистрибутиве, попытавшись ее установить. Например, в CentOS:

sudo yum install logrotate

Или в Ubuntu и основанных на ней дистрибутивах:

sudo apt install logrotate

Теперь, даже если утилита не была установлена, вы ее установите. Все основные настройки программы находятся в файле /etc/logrotate.conf, дополнительные настройки, касаемо правил и других возможностей могут быть размещены в папке /etc/logroate.d/. Вы можете размещать все настройки logroatae прямо в основном конфигурационном файле, будет более правильно, если настройки для каждого отдельного сервиса будут находиться в отдельном файле, в папке /etc/logrotate.d/.

Чтобы конфигурационные файлы из этой папки загружались программой, необходимо добавить в основной конфигурационный файл такую строчку:

Просто убедитесь что она там уже есть. Сначала давайте рассмотрим основные директивы, которые мы будем применять во время настройки. Здесь директивы выглядят не совсем обычно, сама директива и определяет что и когда нужно делать, а уже если нужно, ей передаются дополнительные параметры. Чтобы указать как часто нужно выполнять проверку совпадению условий используются такие директивы:

  • hourly — каждый час;
  • daily — каждый день;
  • weekly — каждую неделю;
  • monthly — каждый месяц;
  • yearly — каждый год.

Основные директивы управления и обработки логов:

  • rotate — указывает сколько старых логов нужно хранить, в параметрах передается количество;
  • create — указывает, что необходимо создать пустой лог файл после перемещения старого;
  • dateext — добавляет дату ротации перед заголовком старого лога;
  • compress — указывает, что лог необходимо сжимать;
  • delaycompress — не сжимать последний и предпоследний журнал;
  • extension — сохранять оригинальный лог файл после ротации, если у него указанное расширение;
  • mail — отправлять Email после завершения ротации;
  • maxage — выполнять ротацию журналов, если они старше, чем указано;
  • missingok — не выдавать ошибки, если лог файла не существует;
  • olddir — перемещать старые логи в отдельную папку;
  • postrotate/endscript — выполнить произвольные команды после ротации;
  • start — номер, с которого будет начата нумерация старых логов;
  • size — размер лога, когда он будет перемещен;

Это те основные директивы, которые мы будем использовать. В главном конфигурационном файле находится глобальная конфигурация, директивы, которые будут распространяться на все логи если не было отменено их действие. Каждый лог, который подлежит ротации описывается таким образом:

адрес_файла_лога <
директивы
>

Теперь давайте создадим файл rsyslog.conf в папке /etc/logrotate.d/ и поместим в него настройки для ротации этого лога:

/var/log/messages <
daily
rotate 3
size 10M
compress
delaycompress
>

Эти настройки означают, что ротация журналов будет выполняться ежедневно, и мы будем хранить три последних журнала, более старые копии будут автоматически удаляться. Минимальный размер для ротации — 10 мегабайт, ротация не будет выполнена, если лог не занимает более 10 мегабайт. Будет использоваться сжатие, для всех журналов кроме последнего и предпоследнего. Точно по такому же принципу вы можете настроить ротацию логов для любого из журналов. Нужно создать такую секцию для каждого из логов, которыми вы хотите управлять.

Теперь осталось протестировать как работает наша конфигурация. Для этого запустим утилиту logrotate с опцией -d. Она выведет все, что планируется сделать, но не будет изменять файлы на диске. У нас есть файл /var/log/messages, размером 40 Мегабайт, посмотрим что будет делать утилита:

logrotate -d /etc/logrotate.d/rsyslog.conf

Как видите, программа обнаруживает файл лога и разделяет его на несколько частей. Вы можете убедиться, что logrotate будет запускаться как положено проверив расписание cron:

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

Выводы

В этой статье мы рассмотрели как выполняется настройка logrotate centos или в любом другом дистрибутиве Linux. Работа утилиты не сильно отличается в зависимости от дистрибутивов. Если у вас есть сервер с большой нагрузкой, вам обязательно необходимо настроить ротацию логов. Надеюсь, эта информация была полезной для вас. На завершение видео, о том как выполняется ротация логов в Ubuntu от LPIC:

И еще одно на английском:

Источник

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