Reputation: 96454
I want to put something in the log, but I keep getting
NameError: undefined local variable or method 'logger' for Report:Class
I've tried
logger "hi"
logger 'hi'
logger.info 'hi'
Rails.logger "hi"
but I just get the above error.
I tried adding config.logger = Logger.new(STDOUT)
to my config/environments/development.rb
but that didn't help, still gettng the error.
I am running the method in script/console
... but I exit and enter it each time to reload everything.
Upvotes: 2
Views: 2726
Reputation: 457
You can use the Rails logger outside of Rails models in at least version 2.3.X
.
You might be used to doing the following in your models or controllers:
logger.info "Some debugging info I want to see in my development log."
If you make a regular model that doesn’t inherit from ActiveRecord
, though, you may see the following error:
undefined local variable or method `logger' for #
The solution is to call Rails.logger.info (or debug, or warn) as follows:
Rails.logger.info "Some debugging info I want to see in my development log."
Upvotes: 0
Reputation: 10258
You have to use:
Rails.logger.info 'hi'
Rails.logger
returns a logger instance, and by calling info, warn, error or debug on it with a message, this message is logged with the specified log level.
Within an ActiveRecord or ActionController instance you also have a logger convenience accessor available that returns Rails.logger
.
Upvotes: 3
Reputation: 211560
Unless you have a variable or method called logger
available in the scope you're executing that it won't magically exist. The config
context is short-term, during initialization only.
Rails.logger
is the global where you can usually access it.
Upvotes: 2