Truncating a Log File

In: Computers|Ideas|Linux Tips|OCD|Performance|Programming

13 Jan 2008

I like to keep detailed logs on things, but sometimes they grow out of control. Apache’s access_log file was 8MB. I knew I was never going to need to look through the whole thing, so I wanted to shorten it. I don’t need 100,000 entries, but 500 is a good figure.

I wondered if there was some way I could do this, and how I’d go about writing a shell script to do it. But then something hit me:

tail -n 500 access_log > access_log

Use tail to print the last 500 lines, and redirect it to itself, using a single > to overwrite as opposed to append.

Of course, pay attention to one important gotcha: as I discovered when messing with the system log file, Apache does not like it when a file that it presumably keeps an open handle on randomly disappears, even if for a millisecond. The proper behavior is to stop Apache, truncate the log file, and restart it. (Something like apache2 stop && tail -n 500 access_log > access_log && apache2 start)

Related posts:

  1. Custom LogFormat with Apache
  2. Stumped by (13)Permission denied: file permissions deny server access ?
  3. Digital Photo Recovery
  4. Overcoming Errors
  5. Fun with Shell Commands

Comment Form

On Other Sites

  • Matt: Hey Victor, A couple good resources for you... http://www.scanboston.com/boston.htm is really det [...]
  • victor: Hi i just got a uniden bearcay scanner and have no local or regional frequency directory.just 1 460 [...]
  • Matt: I do use them periodically. I bought a few i760's, for perhaps $10 apiece in a lot, on eBay a while [...]
  • Marin: Did you eventually end up going with an iDEN phones using Direct Talk? I had some i560's a few year [...]
  • Dan: fyi, EOD = explosive ordnance disposal [...]