Clean your development log files every day

October 28, 2012 launchctl OS X Ruby on Rails

Rails applications tend to create a lot of log files in development mode, especially if you’re practicing TDD. If you work with many applications, the logs can take up to several gigabytes of disk space.

And, surely, no one wants to clean those pesky log files manually.

You could set up logrotate to get rid of the logs, but logrotate is a bit overkill for something that can be done with a one-line launchctl task. Save this snippet into ~/Library/LaunchAgents/me.shevtsov.clean-log-files.plist.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- Cleans development log files every day at 5 AM -->
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>me.shevtsov.clean-log-files</string>
  <key>Program</key>        
  <string>/bin/bash</string>
  <key>ProgramArguments</key>
  <array>
    <string>-l</string>
    <string>-c</string>
    <!-- TODO Replace ~/projects with path to your projects directory -->
    <string>find ~/projects -wholename '*/log/*.log' | xargs rm</string>
  </array>
  <key>StartCalendarInterval</key>
  <dict>
    <key>Minute</key>
    <integer>0</integer>
    <key>Hour</key>
    <integer>5</integer>
  </dict>
</dict>
</plist>

Then run

launchctl load ~/Library/LaunchAgents/me.shevtsov.clean-log-files.plist

Why launchctl and not cron? Because cron won’t run missed tasks at a later time, and launchctl will; this task will be run at 5 AM every day, or later – as soon as you wake up your PC.

This tip isn’t limited to Rails logs, of course.

Buy Me a Coffee at ko-fi.com