'How to create a folder (if not present) with Logger.new?
I'm trying to register a new log
@@my_logger ||= Logger.new("#{Rails.root}/log/my.log")
but when I try to generate new folders , to put it inside
@@my_logger ||= Logger.new("#{Rails.root}/log/#{today.to_s}/my.log")
it returns Errno::ENOENT: No such file or directory
May it be a permission problem? How to create a folder (if not present) with Logger.new?
Solution 1:[1]
Try something like this.
dir = File.dirname("#{Rails.root}/log/#{today}/my.log")
FileUtils.mkdir_p(dir) unless File.directory?(dir)
@@my_logger ||= Logger.new("#{Rails.root}/log/#{today}/my.log")
Solution 2:[2]
You can also do this way
directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)
Solution 3:[3]
Automatic creation of logging directories has been deprecated in rails. Here's a code snippet from the Logger.new code:
ActiveSupport::Deprecation.warn("Automatic directory creation for '#{log}' is deprecated. Please make sure the directory for your log file exists before creating the logger. ")
Accepted practice now is to make sure the log file (and directory) exist before creating the logger.
A way to make sure the directory exists ahead of time might be to use code similar to this:
log_file_name = '/path/to/my.log'
unless File.exist?(File.dirname(log_file_name))
FileUtils.mkdir_p(File.dirname(log_file_name))
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | user2622247 |
| Solution 3 | Kevin Bedell |
