From: Michael Garriss Date: 2003-08-02T00:51:02+09:00 Subject: Re: ANN: debugprint Very nice Brian. Can I use this code? >>In message "ANN: debugprint" >> on 03/08/01, Ben Giddings writes: >> >>|Growing out of the discussions about $DEBUG and $VERBOSE, and how >>|they're set from the commandline, I've created a dead-simple >>|"debugprint" library package. You can find it on RAA at: >> >>How about direct messages to $stderr? >> >> > >Why not $deferr ? Or has that distinction been lost now? > >Personally I'd like a way for this logging module to let you easily log to a >file, say, without interfering with stderr; with separate objects logging to >separate files. And I'd also like timestamps. The one I knocked together is >a mixin: > >module Logger >private > def setlog(log=nil,timestamp=nil) > if log.nil? > @logger_proc = proc { |str| $stderr.puts(str) } > elsif log.is_a? Proc > @logger_proc = log > elsif log.is_a? String > @logger_proc = proc { |str| File.open(log,"a") { |f| f.puts(str) } } > elsif log == false > @logger_proc = proc { } > elsif log.respond_to? :puts > @logger_proc = proc { |str| log.puts(str) } > else > raise TypeError, "#{log.class} is not suitable for setlog" > end > @logger_ts = timestamp > @logger_ts = "%b %d %H:%M:%S " if @logger_ts == true > end > > def log(str) > @logger_proc ||= proc { |str| $stderr.puts(str) } > if @logger_ts > @logger_proc.call( Time.now.strftime(@logger_ts) + str ) > else > @logger_proc.call( str ) > end > end > > def debug(str) > log(str) if $DEBUG > end >end > > >So you can use it like this: > >class Foo > include Logger > def initialize > setlog("/tmp/logout", true) > end > def run > log "hello" > end >end >Foo.new.run > >which logs: > >Aug 01 12:46:16 hello > >Note that you can also pass in an arbitary IO or Proc object for logging. > >Regards, > >Brian. > > > >