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
Question
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)
Solution
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
OTHER TIPS
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