Reputation: 1267
I am pretty new in Rails. I need to log some info into a file inside a function from a class derived of ActionController::Base. I only need to append to the file once, but I should make sure any concurrent processes/threads do not destroy my lines. I do not need any fancy time/IP, etc formatting in my logs.
I have been trying to figure out how to create a custom log but I get confused as all available examples derive it from ActiveRecord::Base (see for example this answer). I also checked how to atomically write to a file with File#flock, but I am not sure whether this is what I really need.
Any help pointing me to th right direction will be appreciated!
Upvotes: 0
Views: 236
Reputation: 42
I'd recommend using Ruby's Logger class.
require 'logger'
logger = Logger.new('FILE_PATH_TO_LOG_TO')
logger.level = Logger::Info
Then you can use flock to lock the file and then write out to the file with:
logger.info("INFO_TO_WRITE")
This way you should be able to log what you need to, and make sure there's no competing access.
Another reference: http://ruby-doc.org/stdlib-2.3.0/libdoc/logger/rdoc/Logger.html
or: http://guides.rubyonrails.org/v3.2/debugging_rails_applications.html#the-logger
Upvotes: 1