Working with Logger
I’m not generally a big fan of logfiles. I much prefer the immediacy of seeing problems directly reported on the screen as soon as they happen. If possible, I actually want to be thrown directly into my problematic code so I can take a look around. However, this isn’t always an option, and in certain cases, having an audit trail in the form of logfiles is as good as it’s going to get.
Ruby’s standard library logger is fairly full-featured, allowing you to log many different kinds of messages and filter them based on their severity. The API is reasonably well documented, so I won’t be spending a ton of time here going over a feature-by-feature summary of what this library offers. Instead, I’ll show you how to replicate a bit of functionality that is especially common in Ruby’s web frameworks: comprehensive error logging.
If I pull up a log from one of my Rails applications, I can easily show what I’m talking about. The following is just a small section of a logfile, in which a full request and the error it ran into have been recorded:
Processing ManagerController#call_in_sheet (for 127.0.0.1 at 2009-02-13 16:38:42) [POST] Session ID: BAh7CCIJdXNlcmkiOg5yZXR1cm5fdG8wIgpmbGFzaElDOidBY3Rpb25Db250 %0Acm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--2f1d03dee418f4c9751925da42 1ae4730f9b55dd Parameters: {"period"=>"01/19/2009", "commit"=>"Select", "action"=>"call_in_sheet", "controller"=>"manager"} NameError (undefined local variable or method 'lunch' for #<CallInAggregator:0x2589240>): ...
Get Ruby Best Practices now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.