Linux обнулить лог файл

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?

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)

(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:

for f in file1 file2 . ; do # pick your favourite emptying method done 

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

Источник

How to Empty System Log Files in Linux

Logging is a normal operation that the Linux operating system performs constantly to maintain different types of messages in various log files.

Читайте также:  Linux скрипты init d

If you’re maintaining a Linux server, it’s most likely that you might have come across an issue of running out of disk space. In such a situation, emptying huge log files mainly resolve the problem.

Using the rm command to directly delete log files is what you should avoid as it can leave you in a messed up situation. In this article, we’ll see various methods to clean up log files in Linux without deleting the actual file entirely.

Create A Sample Log File

Before we jump to the main topic, let’s first create a sample log file on which we’re going to perform operations. The same steps you can follow for your desired log files by using the sudo privileges.

To make a sample log file, you can use the fallocate utility using the below command:

It will give us a file with a 5MB size, which you can verify using the ls command.

List Files by Size in Linux

Clear Logs in Linux Using Cat Command

Concatenating the popular cat command with the /dev/null device file in Linux, you can easily empty the content of a log file.

In case you don’t know, /dev/null is a special file in Linux that helps in disappearing anything written or streamed to it returning the empty output.

To clear or empty any log file, just issue the following command.

$ cat /dev/null > app.log $ ls -lh app.log

Clear Log File in Linux

As you can see, instead of completely deleting the file, the command only removed the file content making its size zero.

Use Redirection Operator To Clear Log In Linux

Redirection Operator (>) is one of the easiest ways to empty the log files in the Linux operating system. Just using the redirection operator with the log filename on the right side and nothing on the left side redirects Null to the file by making it blank.

Empty Log File in Linux

Empty Log File Using ‘true’ Command In Linux

Attaching the colon (:) symbol to the left of the redirection operator makes another built-in true command that also does the same work as the redirection operator.

You can use it as given below:

Likewise, you can add true in place of :> symbol to perform the same task.

Clear Logs in Linux Using Truncate Command

As the meaning of the name says “removing part of something”, truncate is also yet another Linux utility that helps to free up space by shrinking the size of the file without deleting the file entirely.

You can utilize the truncate Linux command with the -s option that defines the file size to empty a file content. Giving a size of zero (0) is equivalent to making file content NULL or adjusting the file size to 0 bytes.

Читайте также:  Узнать мат плату linux

Clear Logs Using Truncate Command

As you can see in the above screenshot, we create a file app.log with a size of 5MB. Then, using a truncate command, we readjusted its size to zero without deleting the file itself.

Clear Log In Linux Using dd Command

I’m sure you must have used the dd (disk/data duplicator) command line utility to create a bootable USB without destroying your disk. The way you copy an image file to a USB boot drive, likewise, you can write blank off to your log file by just changing the input and output file.

Clear Logs Using dd Command

Here, “if” denotes the input file that you want to write to the output file as denoted by “of” .

Truncate Logs In Linux Using Echo Command

The echo command is mainly used to print or send messages in the terminal. The same functionality of the echo command can utilize to send a null output to the log file.

Simply run the below command to redirect the empty to the file:

$ echo "" > app.log Or $ echo > app.log

Truncate Logs In Linux

However, if you see in the above screenshot, the file size is still not zero meaning the file is not completely empty. This is because we redirected an empty string which is not the same as NULL.

So, to send a null output to the file and make file size zero, you also need to use the -n flag with the echo command that restricts any trailing newline or leaving any empty line as happened in the above case.

Now the file size becomes zero and there is no content in the log file.

Clear Logs In Linux Using Logrotate Tool

Coming to the last and considered one of the best-automated methods, you can also use a logrotate tool that is built specifically to manage logs. It helps in the automatic rotation, compression, and removal of log files.

Check out the separate article on how to rotate logs with Logrotate in Linux for more information.

Finally, we learned to use different command line utilities to clear logs without deleting the files entirely in the Linux operating system. You can explore each command separately to use it along with Cronjob to automate the clean-up of logs at regular intervals of time.

Источник

Чистим Логи (*.log) на linux серверах

Чистим Логи (*.log) на linux серверах

В последнее время на сервере мало места свободного, и если за ним не следить часов 12-20 — место может закончится, что приходится не только чистить все бэкапы БД на сайтах, но и логи. Чтобы постоянно не гуглить — добавлю заметку для себя в блоге, как через SSH быстро можно почистить логи сервера.

Удалять файлы нельзя. Файлы требуется «обнулять» (удалять содержимое). При удалении файла некоторые службы у Вас не запустятся. Обнулить log файл Вы можете командой:

cat /dev/null > /var/log/mysqld.log

где /var/log/ — путь к файлу лога, и mysqld.log файл лога

Читайте также:  Отключить проверку файловой системы при загрузке linux

Обнулить все log файлы в папке: перейдите в требуемую папку командой cd

cd /var/log cd /var/log/audit cd /var/log/exim cd /var/log/ConsoleKit cd /var/log/httpd cd /var/log/nginx cd /var/log/ntpstats cd /var/log/pmta cd /var/log/qemu-ga cd /var/log/roundcubemail cd /var/log/sa cd /usr/local/vesta/log
find -maxdepth 1 -type f -name '*' -exec dd if=/dev/null of={> 2>/dev/null \;

Архивы *.gz в лог папках — можно смело удалят.

Для регулярного обнуления логов Вы можете создать задание Cron. Перед обнулением файла Вы можете архивировать его текущее содержимое, например, командой

gzip -v9f $log_file > $log_file.gz

Источник

Как очистить файл журнала в Linux

Favorite

Добавить в избранное

Как очистить файл журнала в Linux

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

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

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

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

4 способа очистить файл в Linux

Существует несколько способов очистки файла без его фактического удаления. Позвольте нам показать вам некоторые из этих методов.

Способ 1: усечь файл с помощью команды truncate

Самый безопасный способ обрезать файл журнала — использовать команду truncate.

В приведенной выше команде -s используется для установки/настройки размера (в байтах) файла. Когда вы используете -s 0, это означает, что вы изменили размер файла до 0 байт.

Способ 2: Пустой файл, используя :> или >

Самый простой способ очистить файл — использовать команду ниже. Если файл не используется, он будет работать в Bash:

Хотя вышеперечисленное работает только в Bash Shell, вы можете использовать аналогичную команду для других оболочек:

Вы также можете использовать эту команду для очистки файла:

Способ 3: использование команды echo для очистки файла в Linux

Другой способ очистить файл — использовать команду echo в Linux:

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

Способ 4: используйте /dev/null, чтобы очистить файл

Вы также можете использовать знаменитую /dev/null и объединить ее с командой cat для очистки файла журнала:

И если у вас недостаточно прав для какой-либо из вышеперечисленных команд, это верный выстрел, но немного грязный способ добиться этого:

touch newfile mv newfile filename

Мы надеемся, что этот быстрый совет помог вам очистить файл в Linux. Добавьте нас в закладки для получения дополнительных советов по Linux.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

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