From: Chuck Remes Date: 2009-07-22T01:55:46+09:00 Subject: Re: Best practice question: logging On Jul 21, 2009, at 9:50 AM, Pito Salas wrote: > I want to sprinkle my code (Ruby, not Rails) liberally with logging > calls so that when things go wrong I can see what happened. > > - is Ruby's Logger class the best practice to use, or is there another > that's cooler? For example it looks like Logger is not that flexible > about changing the format of log entries. > > - Is it better to define a global $Logger variable to hold the new > Logger object across classes and methods, or bettor to do a @l = > Logger.new(STDOUT) in each class's initializer? > > - how do I minimize the overhead when logging is OFF? > > - is one of these idioms faster than the other: > > if debugging > @l.debug("wow, what was that?" > end > > @l.debug("wow, what was that?" if debugging > > @l.debug # no condition, just set @l.level = Logger::ERROR > > Any other tips or pointers would be greatly appreciated! I asked this same question about a year ago and got lots of help. Here is what I created: http://gist.github.com/151454 I didn't write a lot of documentation in these classes and modules. Hopefully the concepts are clear enough from the code provided. Logging is a pretty interesting process in my opinion. You may just write messages to STDOUT, to a file, to a network socket, or all of the above. Also, sometimes you want to disable logging but adding "logger.log("some message") unless logger.disabled?" all over the place is very ugly. As such, I use the Null Object pattern so you can "switch out" the logging class behind the scenes to one that just drops all messages. For live logging, you call Logger.make_live (class method). To disable logging, Logger.make_null. If you have specific questions on this code, reply back. I haven't looked at in since I wrote it 1+ years ago but I'm sure I can answer any questions that arise. cr