简体   繁体   中英

Logging to my own file in Rails from an ActionController?

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM