0

I want to be able to log things to my Rail's app logs from a ruby class.

I was hoping to do logger.info "some stuff" from a class in my_app/app/myClass.rb, but it's not defined. When I use logger in my controllers and elsewhere it works.

I'm a bit new to Rails / Ruby, and I'm assuming this is simply because the logger class isn't included in myClass.rb, but it is automatically included in all controllers, models, etc.

How can I include the logger class in an arbitrary ruby class, or otherwise log to my rails app from a ruby class?

(Added tag for "Pundit" since specifically I am using logger in a Pundit policy file, but it's just a ruby class :P)

Don P
  • 60,113
  • 114
  • 300
  • 432
  • i just did this the other day and this helped me out. http://stackoverflow.com/questions/917566/ruby-share-logger-instance-among-module-classes – Eric Apr 24 '14 at 15:02

2 Answers2

0

If you want to create your own logger:

class MyClass
  def initialize
     @app_logger = Logger.new("#{Rails.root}/log/app.log")
  end

  def othermethod
     @app_logger.info("anything here")
  end 
end 
Raj
  • 22,346
  • 14
  • 99
  • 142
  • Wouldnt this only be usable in files that were loaded after application controller? – Don P Apr 24 '14 at 14:57
  • 1
    what you mean by doesnt work? what is the error message? – Raj Apr 24 '14 at 15:00
  • NameError (undefined local variable or method `app_logger' for #). Which is the same error when `logger` isn't defined. Again I think this is due to this class being loaded before application_controller, which is why logger isn't available either – Don P Apr 24 '14 at 15:01
  • if you are going to use the logger only in this class, initialize app_logger in this class – Raj Apr 24 '14 at 15:02
  • Thanks for the update. Now I'm not getting an error any more, but this still doesn't log anything to the app logs. – Don P Apr 24 '14 at 15:07
  • `@app_logger = Logger.new("#{Rails.root}/log/app.log")` and `@app_logger.info('testing app logger')` in my initialize – Don P Apr 24 '14 at 15:08
  • try creating an empty app.log file in log directory – Raj Apr 24 '14 at 16:50
0

You can load the app's logger into a method on Object during the rails app initialization process

# config/initializers/my_logger.rb

class Object
  def mylog
    @logger ||= Rails.logger
  end
end

Enhancing / changing the Object class should be done with care

New Alexandria
  • 6,951
  • 4
  • 57
  • 77