Linux clear all log files

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.

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.

Читайте также:  Как создать папку пользователя linux

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.

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” .

Читайте также:  Linux разрешение экрана xorg

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.

Источник

How to truncate all logfiles?

can anybody give me a solution to truncate all logfile in /var/log/ directory? and a question just for knowledge, is it a good idea or not?

#!/bin/bash LOGDIR="/var/log" for logfile in $(ls $LOGDIR/*log) do truncate -s 0 $logfile done 

It’s NOT a good idea — /var/log is where the system puts messages you might need later. Ubuntu has encountered the problem before. Read man 8 logrotate;man logrotate.conf .

5 Answers 5

if you want to do this more than once you should use logrotate to handle your logs. Usually it’s installed in ubuntu. Have a look at man logrotate (or if you do not have it installed look at the online manpage or install it with sudo apt-get install logrotate )

logrotate is designed to ease administration of systems that generate large numbers of log files. It allows automatic rotation, compression, removal, and mailing of log files. Each log file may be handled daily, weekly, monthly, or when it grows too large.

If you want to clear all your log files, not just those in the first-level log folder, you could use:

shopt -s globstar # if needed truncate -s 0 /var/log/*.log # first-level logs truncate -s 0 /var/log/**/*.log # nested folders, like /var/log/nginx/access.log 

Noting that if you already have logrotate running, you’ll need to clear out the rotated .gz logs as well:

find /var/log -type f -name '*.15.gz' -exec rm <> + 

A valid use for this could be building a VM appliance container for distribution, for example.

Читайте также:  Linux mint оболочка установить

You should not need to do this as part of routine maintenance: as D-E-N quite correctly suggested, use logrotate for that.

This will find all log files in /var/log and truncate them to 0 bytes.

find /var/log -type f -iname '*.log' -print0 | xargs -0 truncate -s0 

I would use *.log* instead but I’m not sure if it’s 100% safe, so I haven’t included it in the answer. Because there are files like dovecot.log-20180930 and dovecot.log-20180923.gz .

There’s couple methods to fully truncating a file, generally applicable to most POSIX-compliant OS. Most common that you’ll see with shell scripting is something like true > file.txt or : > file.txt ( and in case of bash shell, > redirection alone is sufficient ). That’s due to the way how > opens files via open() or openat() syscall with O_WRONLY|O_CREAT|O_TRUNC flags — that reads write-only OR create if filename doesn’t exist, OR truncate existing filename.

With that in mind, we can implement something like that in C ourselves:

#include #include #include int main(int argc, char **argv) < if (argc == 2)< int fd = open(argv[1],O_TRUNC); close(fd); >return 0; > 

Name the file that stores this code as trunc.c and compile that with gcc trunc.c -o trunc , and you have yourself a small utility that will truncate a filename argument it’s provided as in trunc ./foobar.txt . Of course, this code doesn’t do other checks, it only truncates first positional parameter. I’ll leave it up to the readers to figure out how to deal with more than one positional parameter. On side note, there is truncate() syscall which we could use as well, and truncate a file to variable length.

Now, if you are not a fan of C, Python might be easier for you. open() command operates on the same principle in Python — opening file for writing and truncating if filename exists. Thus we can do

python -c 'import sys;open(sys.argv[1],"w").close()' passwd.copy 

As for finding all .log files, that’s been covered in other answers already — use * glob or extended glob in bash . There’s also find -type f -name «*.log» , which has -exec flag for running commands (in this particular case sh -c » to take advantage of > because > is a shell operator and not an external executable). Thus you can do

find /var/log -type f -name "*.log" -exec sh -c 'true > "$1"' sh <> \; 

It’s also worth noting that log files in directory such as /var/log often are rotated by logrotate service, so there will be filenames such as /var/log/service.log , /var/log/service.log.1 , etc , so you may want to use *.log.9 pattern instead

Among other things, we can copy /dev/null into the desired file. Oddly enough, even though /dev/null is a special character device type of file, when you copy that elsewhere the result is empty regular file, at least with GNU cp . Thus we can do

Источник

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