Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configurable ruby logger setup: Logger.new().level = variable

I want to change the logging level of an application (ruby).

require 'logger'

config = { :level => 'Logger::WARN' }

log = Logger.new STDOUT
log.level = Kernel.const_get config[:level]

Well, the irb wasn't happy with that and threw "NameError: wrong constant name Logger::WARN" in my face. Ugh! I was insulted.

I could do this in a case/when to solve this, or do log.level = 1, but there must be a more elegant way!

Does anyone have any ideas?

-daniel

like image 878
Daniel Avatar asked Apr 05 '10 15:04

Daniel


1 Answers

Why don't you just use the literal constant in your config hash?

config = { :level => Logger::WARN }

Then you don't have to fool around with const_get or anything like that; you can simply do log.level = config[:level].

If it absolutely must be a string, you can drop the namespace prefix and call const_get on the Logger module:

irb(main):012:0> Logger.const_get 'WARN'
=> 2

If it really really has to be the qualified string, you might try using this blog's qualified_const_get method (which is not a built-in!).

like image 53
Mark Rushakoff Avatar answered Oct 16 '22 19:10

Mark Rushakoff