Drupal Logging: The Watchdog

22 Mar 2010
Posted by jcfiala

When I first started working in Drupal, I was astonished to hear that the logging function that Drupal provides is called - of all things - watchdog(). I complained that it was a bad name, but continued using it, along with the dblog module, happily throwing things into the watchdog table and looking them up there.

What I didn't realize until recently, is that watchdog isn't just one storage system - its several. And, you can play with it. As you'll have seen if you followed the link cleverly hidden in the last paragraph, calling watchdog doesn't directly write anything anywhere. Instead, it fires off the watchdog event, finding all of the modules implementing hook_watchdog, and letting them handle the bundle of log data and do anything with it they want. The core module dblog writes it to the watchdog table, and the syslog module passes the log info to the operating system's logs via the syslog() function. If you wanted, you could even have both of them on at the same time.

But this also means, you can have a module that pays attention to the watchdog and reacts to what it's receiving. In the simplist way, and the way I've recently worked with it, I created a log that keeps track of what searches have been made. Happily, the search module(s) write to the watchdog every time someone does a search, with the search being attempted. However, the watchdog itself slowly deletes it's long history from memory as time goes on, and as such search data from a few months ago can easily disappear before you realize it.

But - we have hook_watchdog. So, I implemented a simple module, using (mostly) the same table defined in the dblog module, writing only the search log messages out - copying down only those items we wanted to save, but saving them forever.

That's not the only thing you could do with hook_watchdog, of course. If you had a highly important website, you could create a module looking for WATCHDOG_EMERG, WATCHDOG_ALERT and WATCHDOG_CRITICAL messages, and then use SMS or email to send the errors to you as they happen. The important thing I'm saying here, though, is that watchdog is more than a simple logging function, and if you need to pay attention to what your site's doing, this is a way to keep an eye on it. But do keep in mind that watchdog can get called a lot in certain situations, so make sure you're doing as little as possible on each call.

Tags: