Ruby-on-rails 如何使用 Logger.new 创建文件夹(如果不存在)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15096219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a folder (if not present) with Logger.new?
提问by Mauro Dias
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
它返回 Errno::ENOENT: No such file or directory
May it be a permission problem? How to create a folder (if not present) with Logger.new?
可能是权限问题?如何使用 Logger.new 创建文件夹(如果不存在)?
回答by Mikhail Nikalyukin
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")
回答by user2622247
You can also do this way
你也可以这样做
directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)
回答by Kevin Bedell
Automatic creation of logging directories has been deprecated in rails. Here's a code snippet from the Logger.new code:
自动创建日志目录已在 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. ")
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

