Skip to content

Rogger 0.1.2 Released

Posted on:January 7, 2016

Rogger v0.1.2 has been released - a patch that makes logging to Graylog2 even easier.

For example, in a Rake task you can do something like:

namespace :my_tasks do
  task :first_task => :environment do
    Rogger.debug "This is a debug message"
    Rogger.info  "This is a info message"
    Rogger.warn  "This is a warn message"
    Rogger.error "This is an error message"
    Rogger.fatal "This is a fatal message"
 
    Rogger.info do
      { short_message: "Don't forget to include a short message as required by GELF", custom_key: "This is a custom key-value pair that will be parsed by Graylog2", custom_key2: "This is a another one" }
    end
 
    Rogger.log_exceptions do
      x = 1/0 # will raise a ZeroDivisionError that will be logged
    end
 
    Rogger.log_exceptions! do
      x = 1/0 # will log the exception and rethrow the exception
    end
  end
end

Notably, this is also the first time ever that I’m using metaprogramming in actual code. The actual bit is below:

::GELF::Levels.constants.each do |const|
  module_eval <<-EOT, __FILE__, __LINE__ + 1
    def self.#{const.downcase}(msg = "", &block)
      @@logger.#{const.downcase}(msg, &block)
    end
  EOT
end

This bit defines the debug, info etc. module-level methods that you see above using module_eval, encapsulating @@logger singleton’s methods as module methods instead. These levels correspond to Rails log levels and are used elsewhere in gelf as well, so Rogger takes advantage of that.

The user, then, does not have to deal with the actual GELF logger instance, as is already the case pre 0.1.2 (Rogger hooks onto the Rails logger by using ActiveSupport::Logger.broadcast).