How to create a folder (if not present) with Logge

2019-03-17 23:08发布

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?

3条回答
Luminary・发光体
2楼-- · 2019-03-17 23:43

You can also do this way

directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)
查看更多
3楼-- · 2019-03-17 23:50

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")
查看更多
劫难
4楼-- · 2019-03-17 23:53

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
查看更多
登录 后发表回答