我正在尝试注册新日志
@@my_logger ||= Logger.new("#{Rails.root}/log/my.log")
但是当我尝试生成新文件夹时,将其放入
@@my_logger ||= Logger.new("#{Rails.root}/log/today.to_s/my.log")
返回Errno::ENOENT: No such file or directory
可能是许可问题吗? 如何使用Logger.new创建文件夹(如果不存在)?
答案 0 :(得分:41)
尝试这样的事情。
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")
答案 1 :(得分:11)
您也可以这样做
directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)
答案 2 :(得分:4)
rails中已弃用自动创建日志记录目录。这是Logger.new代码中的代码片段:
ActiveSupport::Deprecation.warn("Automatic directory creation for '#{log}' is deprecated. Please make sure the directory for your log file exists before creating the logger. ")
现在接受的做法是在创建记录器之前确保日志文件(和目录)存在。
确保目录提前存在的方法可能是使用与此类似的代码:
log_file_name = '/path/to/my.log'
unless File.exist?(File.dirname(log_file_name))
FileUtils.mkdir_p(File.dirname(log_file_name))
end