Tuesday, February 15, 2011

Linux: Clear a log file without breaking things

Often when troubleshooting or debugging a problem with a service you will need to work with one or more log files that has been accumulating cruft for some time unspecified time.

This happened to me when trying to fix a mail server issue. I found myself working with a raw mail log that accumulated every detail of every connection to a production server. While I could search the log for key terms, the volume of data resulted in plenty of false positives for any reasonably short query string. Since most of the data was noise from processes working fine, I found the easiest thing to do was clear the log, try the failing action, view the short log, rinse, grumble and fumble with obscure MTA settings, repeat.

Inappropriate touching


My first instinct was to sudo rm maillog then touch maillog after a moment of consideration, I realized this is a really bad idea. Why? The maillog file is owned by the mail server user (zimbra in my case) and has very specific permissions set on it. In order to properly re-create it, I would have to su zimbra touch maillog then chmod the permissions back the way they should be. Even then I might miss something.

A Better Way to Purge


The Zimbra wiki had a much better, one-line solution:
sudo cat /dev/null > maillog

This quick little one-liner has the desired effect of clearing the the log while retaining permissions and other file properties that removing the file would destroy. There's also something kinda cool about how this works.

Using the cat command causes the supplied file to be dumped to standard output (in this case /dev/null -- which is a pseudo-device -- but also, a file since everything in Linux is a file).

The output of cat /dev/null is guaranteed to be exactly nothing. The greater than redirection operator ( >) says push the output to the specified file, replacing all existing content. Poof. Empty log file with permissions preserved.

I can see being a handy tool to have laying around....Catalina.log I'm looking in your direction....


No comments:

Post a Comment