An Introduction to Logging

Installation

$ gem install logging
#  Successfully installed logging-1.6.1
#  1 gem installed
#  Building YARD (yri) index for logging-1.6.1...

Features

Here we create individual logging objects rather than one monstrous global logger [1]. Once they have been individually created you can customize the behavior of each.

require 'logging'

 Logging.logger.root.level = :warn

 Logging.logger.root.appenders = Logging.appenders.stdout

 log1 = Logging.logger['log1']
 log2 = Logging.logger['log2']

 log2.level = :debug

 log1.info "This will not be shown."
 log2.info "This will be shown."

Here we use multiple appenders [2]. Appenders allow you to shunt your logging messages to different output media. Here we set our messages to log to standard out and to a file.

require 'logging'

log1 = Logging.logger['log1']

log1.add_appenders(
    Logging.appenders.stdout,
    Logging.appenders.file('example.log')
)
log1.level = :info

log1.debug "this debug message will not be output by the logger"
log1.info "just some friendly advice"

Here we create log objects at initialization of class Foo and Foo::Bar [3]. Once we've done that we can refine our logging parameters to reveal behavior specific to each class.

require 'logging'

Logging.logger.root.appenders = Logging.appenders.stdout
Logging.logger.root.level = :info

class Foo
  attr_reader :log
  def initialize; @log = Logging.logger[self]; end
end

class Foo::Bar
  attr_reader :log
  def initialize; @log = Logging.logger[self]; end
end

foo = Foo.new.log
bar = Foo::Bar.new.log

# you'll notice in these log messages that the logger names were taken
# from the class names of the Foo and Foo::Bar instances
foo.info 'this message came from Foo'
bar.warn 'this is a warning from Foo::Bar'

Incorporating Rails

Incorporate rails easily with the logging-rails gem [4].

gem 'logging-rails', :require => 'logging/rails'
rails generate logging:install

Thanks for Watching

This was my first screen-cast so thank you for bearing with me. The production quality on my next cast should be markedly increased as I have learned much by making this one. The Logging framework has a lot to offer and I hope that you've found this helpful. Thanks.

References

1.) Custom Loggers
2.) Appenders
3.) Class Loggers
4.) logging-rails

Additional References

TWP Logging GitHub
Ruby Rogues episode 025
Scroll Blindness
Pry an alternative to IRB
Extending Rails 3 with Railties, 2010

blog comments powered by Disqus