Simple (syslog) logging with Ruby

Here’s a tip that took me a while to figure out, but is really easy in retrospect. So easy in fact that I just assumed I was being dense for not knowing it, and everyone else just “knew” this.

However, after a smart friend tweeted about needing a simple logging method, and not getting any replies that nailed it, I thought I’d post this up.

First, require syslog

require 'syslog'

Then, make a call to Syslog.open, with a block and send a message

Syslog.open($0, Syslog::LOG_PID | Syslog::LOG_CONS) { |s| s.warning "Danger!" }

In this case I went with a warning level message. Syslog also supports:

  • crit CRITICAL system level events (like “System is going down…”)
  • emerg emergency
  • alert
  • err
  • warning
  • notice
  • info
  • debug

These map directly to the syslog levels you can read about in “man syslog”

It seems that debug and info messages don’t make it to the os x console app, so I use warning.

Here’s the code all together:

And that’s IT! Pretty simple way to get logging into any of your scripts. Don’t want it in main syslog? Just edit your syslog configuration and divert all messages from your app into a dedicated log file (without needing to touch your script).