On 4/13/07, Robert Dober <robert.dober / gmail.com> wrote:
> Hi list
>
> this is incredibly simple, but I just wanted to know what you think about it.
>
> I really often write the following code
>
> puts <whatever> if $DEBUG
>
> I guess you all do that to some extent, James just talked a newbie
> into it recently ;)
>
> The first programmer's virtue of course makes me do some things like
> def debug *args, &blk
>    return unless $DEBUG
>   <do something incredibly smart with the args ;)>
> end
> and sometimes on some of my machines I will do something like
>
> require 'ilmig/tools/debug'
>
> I feel that this might be so common place that a Kernel::debug or
> whatever other suitable name might be a good idea.
>
> I am listening .... ;)
>

For medium to large programs having a global $DEBUG flag is going to
create lots of "line noise" as all those debug messages go whipping
by.

I much prefer the fine grained control that the 'logging' and 'log4r'
packages give you.


require 'logging'

class A
  def initialize
    @log = Logging::Logger[self]
    @log.debug "new object created '#{self.object_id}'"
  end
end

class B
  def initialize
    @log = Logging::Logger[self]
    @log.debug "new object created '#{self.object_id}'"
  end
end

Logging::Logger['A'].level = :warn
Logging::Logger['B'].level = :debug


It's a little more setup, but you have far greater control over what
gets logged and what doesn't. The framework also takes care of
timestamps, outputting class info, etc.

And if you don't want all that complexity, there is always the core
Logger class that comes with Ruby.

Blessings,
TwP