Как почистить логи в linux
Перейти к содержимому

Как почистить логи в linux

  • автор:

Sorry, you have been blocked

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

What can I do to resolve this?

You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.

Cloudflare Ray ID: 7a24de0d58792d73 • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare

How to clean log file? [duplicate]

Is there a better way to clean the log file? I usually delete the old logfile and create a new logfile and I am looking for a shorter type/bash/command program. How can I use an alias?

Micromega's user avatar

1 Answer 1

(fell free to substitute false or any other command that produces no output, like e.g. : does in bash ) if you want to be more eloquent, will all empty logfile (actually they will truncate it to zero size).

If you want to know how long it «takes», you may use

(which is the same as dd if=/dev/null > logfile , by the way)

You can also use

(or truncate -s 0 logfile ) to be perfectly explicit or, if you don’t want to,

(in which case you are relying on the common behaviour that applications usually do recreate a logfile if it doesn’t exist already).

However, since logfiles are usually useful, you might want to compress and save a copy. While you could do that with your own script, it is a good idea to at least try using an existing working solution, in this case logrotate , which can do exactly that and is reasonably configurable.

Should you need to do it for several files, the safe way is

Some shells ( zsh ) also allow one to specify several redirection targets.

This works (at least in bash ) since it creates all the redirections required although only the last one will catch any input (or none in this case). The tee example with several files should work in any case (given your tee does know how to handle several output files)

Of course, the good old shell loop would work as well:

although it will be much slower due to the command being run separately for each file. That may be helped by using find :

Какие файлы можно удалить при нехватке места на диске Linux

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

Предупрежу заранее: следующие команды хотя в основном и удаляют бесполезные файлы, после их выполнения могут привести к следующим последствиям:

  • потребуется перезапуск служб для их нормальной работы (чтобы они заново пересоздали файлы журналов, кэши, файлы блокировки)
  • могут быть потеряны различные журналы и файлы из корзины, которые хотя и не нужны большинству пользователей, в некоторых условиях вы можете захотеть их оставить (например, вам важно изучить файлы логов, поскольку в них может быть причина проблемы).

Это означает, что НЕ копируйте бездумно команды — читайте пояснения к ним и оценивайте, насколько они безболезненны для вашей ситуации.

1. Удаление временных файлов

Файлы в папке /tmp/ будут удалены в любом случае при следующей перезагрузки системы. То есть с одной стороны их можно удалить достаточно безболезненно:

НО: может быть нарушена работа программ, которые запущены в настоящее время и которые сохранили какие-то данные в папку /tmp/.

2. Удаление файлов кэширования

В директории /var/cache/ много поддиректорий, которые можно удалить практически безболезненно (данные утеряны не будут, а программы создадут новые файлы кэширования). Эта директория вызывает особый интерес, поскольку на некоторых системах кэши разрастаются на гигабайты и десятки гигабайт. Иногда поиск проблемной директории в /var/cache/ может окончательно решить ситуацию с нехваткой места на диске.

Для удаления кэша шрифтов:

Для удаления кэша установочных пакетов (на Debian, Linux Mint, Ubuntu, Kali Linux и их производных):

Для удаления кэша установочных пакетов (на Arch Linux, BlackArch и их производных):

Удаление кэша справочных страниц:

Вы можете продолжить поиск больших кэшей применимо к программному обеспечению, установленному на вашей системе. Например, это могут быть кэши веб-сервера, прокси-сервера и т. д.

3. Удаление логов (журналов)

В этой папке (/var/log/) можно удалить практически все файлы, но старайтесь сохранить структуру папок, поскольку некоторые приложения после удаления здесь папки не в состоянии создать её второй раз…

На веб-серверах могут разрастись слишком сильно журналы веб-сервера.

Для удаления логов Apache на Debian, Linux Mint, Ubuntu, Kali Linux и их производных:

Для удаления логов Apache на Arch Linux, BlackArch и их производных:

Чтобы сервер начал создавать новые файлы журналов и записывать в них, нужно перезапустить службу веб-сервера.

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

4. Очистите корзину

Этот совет больше для настольных систем. Файлы, которые вы удалили в графическом интерфейсе рабочего стола, попадают в папку

/.local/share/Trash/files/, вы можете проанализировать их и при желании удалить (второй раз):

5. Удаление ненужных файлов исходного кода заголовков ядра

Следующее актуально только для Debian, Linux Mint, Ubuntu, Kali Linux и их производных. Проверьте папку /usr/src/, там будут подпапки вида linux-headers- — большинство из них можно удалить — оставьте только ту, номер которой соответствует текущему ядру системы — обычно это самый последний номер выпуска.

6. Удаление осиротевших пакетов

Осиротевшие пакеты — это те пакеты (программы), которые устанавливались в качестве зависимостей для других программ. Но по разным причинам они больше не нужны: или удалена программа, которая их использовала, или для той программы они перестали быть зависимостями после обновления программы.

На Debian, Linux Mint, Ubuntu, Kali Linux и их производных удалить ненужные пакеты можно следующим образом:

Для Debian и производных предыдущая команда абсолютно безопасна.

В Arch Linux и производных список осиротевших пакетов можно увидеть следующим образом:

Прежде чем переходить к их автоматическому удалению, настоятельно рекомендуется изучить этот список!

Для рекурсивного удаления сироток и их конфигурационных файлов в Arch Linux и производных:

Если осиротевшие пакеты не были найдены, pacman завершит работу с ошибкой: ошибка: не задано целей (для справки используйте -h). Это ожидаемо, поскольку pacman -Rns не получил аргументов.

7. Очистка журналов systemd

Со временем, в некоторых системах логи системы начинают занимать гигабайты на жёстком диске. Просмотреть журналы и освободить место вы можете с помощью команды journalctl, подробности смотрите в статье «Как использовать journalctl для просмотра системных логов Linux».

Чтобы увидеть, сколько место занимают журналы, выполните:

Чтобы удалить все записи, оставив только записей на 100 мегабайт, выполните:

Либо для удаления всех записей в системном журнале, старше одной недели:

8. Файлы в директории /lost+found

В папку /lost+found сохраняются файлы, которые были найдены после проверки файловой системы диска. Обычно такие проверки выполняются после внезапной перезагрузки системы или в случае признаков проблем с диском.

Найденные файлы обычно повреждены. Их цель — сохранить данные, которые в случае исправления ошибок на файловой системе были бы совсем утеряны.

Папка /lost+found может быть пустой (если не было проблем с диском). В случае если там есть файлы, то вы можете их просмотреть и, при желании, удалить.

9. Очистка PHP сессий

Иногда веб-приложений из-за бага могут создать бесчисленное количество сессий. Проверьте директорию /var/lib/php/sessions/ на предмет слишком большого количества файлов.

(БОНУС) 10. Проанализируйте файлы Docker

Не удаляйте бездумно файлы Docker. Я привожу пример этой директории только по той причине, что она привлекла моё внимание из-за просто фантасмагоричного размера — и это при том, что я Docker'ом фактически не пользуюсь — буквально несколько раз попробовал, чтобы увидеть, что это такое.

Самой большой папкой является /var/lib/docker/overlay2/. Для анализа занимаемого места на диске выполните:

Заключение

Итак, мы рассмотрели, какие файлы можно удалить из Linux практически без потери информации. Кроме рассмотренных директорий, которые можно очистить как на удалённой системе с веб-сервером, так и на домашнем компьютере, пользователям с графическим рабочим столом следует обратить внимание на такие директории как:

Их НЕ нужно удалять, но стоит проанализировать. Например, вы можете выяснить, что веб-браузер на вашем компьютере имеет кэш в несколько гигабайт и что вы можете их освободить (рекомендуется делать средствами веб-браузера, а не удалять файлы напрямую).

Если я пропустил какие-то директории с файлами, которые можно безболезненно удалить, то пишите их в комментариях!

How to Clear Systemd Journal Logs

The systemd journal is systemd’s own logging system. It is equivalent to the syslog in the init system. It collects and stored kernel logging data, system log messages, standard output, and errors for various systemd services.

A Linux machine with systemd writes the logs to /var/log/journal directory. If you remember the Linux directory structure, /var is where the system logs are stored.

You can either manually view the log files using less command or use the journalctl command. To view all the latest logs, use the command with the reverse option.

The thing with logging is that over time, it starts to grow big. And if you check the disk space in Linux, you’ll see that sometimes, it takes several GB of space.

Let me show you how to clean systemd journal logs and free up disk space on your Linux system.

Clearing systemd journal logs

Clear Logs Linux

First, check the space taken by journal logs with the du command:

You can also use the journalctl command for the same task:

Both commands should give approximately the same result:

Now that you know how much space the journal logs take, you can decide if you want to clear the logs or not. If you decide to clear the journal logs, let me show you a couple of ways of doing it.

You can, of course, use the rm command to delete the files in the log folder but I won’t advise that. The journalctl command gives you the proper way of handling old logs.

First thing you should do is to rotate journal files. This will mark the currently active journal logs as archive and create fresh new logs. It’s optional but a good practice to do so.

Now you have three ways to clear old journal logs. You delete logs older than a certain time, or you delete older log files so that the total log size is limited to the predefined disk space, or you limit the number of log files. Let’s see how to use all three methods.

1. Clear journal log older than x days

Keep in mind that logs are important for auditing purposes so you should not delete all of them at the same time. Let’s say you want to keep the log history of just two days. To delete all entries older than two days, use this command:

Here’s what the output may look like:

You can also change the provide time frame in hours like 2h, in minutes like 2m, in seconds like 2s. If you want bigger time units, you can 2weeks, 2months as well.

2. Restrict logs to a certain size

Another way is to restrict the log size. This will delete the journal log files until the disk space taken by journal logs falls below the size you specified.

This will reduce the log size to around 100 MB.

You can specify the size in GB with G, MB with M, KB with K etc.

3. Restrict number of log files

The third way is to limit the number of log files. The journalctl usually has log files for the system and for the users. As the logs get old, they are archived in various files.

You can limit the number of archive log files. Let’s say you want to have only five log files.

It will remove the older archive log files leaving only the specified number of log files.

Linux Handbook Abhishek Prakash

Automatically clearing old log files [Requires intermediate knowledge of command line]

What you just did will clean the log files for now. In a month, the logs will increase again. You can manually clean them with one of the methods described above. But that is a tedious task and you may not remember to do that regularly.

The good thing is that you can configure systemd to automatically handle old log files.

The journalctl has configuration file at /etc/systemd/journald.conf. There are settings which are commented out. The commented lines basically indicate the default value of those settings parameters (even if they are commented out).

You can change some of these default settings to automatically clean the log files.

You would want to change the following settings:

Setting Description
SystemMaxUse Max disk space logs can take
SystemMaxFileSize Max size of an INDIVIDUAL log file
SystemMaxFiles Max number of log files

Please note that you should be careful while editing configuration files. You must be comfortable using a terminal-based text editor like Vim, Emacs or Nano so that you don’t make silly mistakes while editing the conf file.

I advise to make a backup of the configuration file first:

Now, you should uncomment (remove the # at the beginning of the line) the setting you want to use. For example, I want to restrict the maximum disk space taken by the log files to 250 MB.

You’ll have to use Vim or some other terminal based editor in order to edit this configuration file. Here’s what it looks like me after editing the file.

Keep in mind that after editing the configuration file, you should load the changes:

The journald.conf file can be used to tweak the journalctl settings even further. You can even set the levels of log (info, debug, error etc) you want to see. It’s up to you if you want to change those settings as well.

Linux Handbook Abhishek Prakash

I hope you like this tip to clear systemd journal log files. If you have any questions or suggestions, please leave a comment below.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *