-4

I am trying to capture errors, check for a /tmp directory and then write the error to a logfile in that directory, currently I get:

.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/fileutils.rb:252:in `mkdir': Permission denied @ dir_s_mkdir - /temp

Here is my code:

require 'logger'
require 'tmpdir'

temp = Dir.tmpdir()
log = Logger.new File.open("#{temp}/error.log", 'w')
log.level = Logger::INFO

begin

rescue StandardError => e
   log.error "Error - #{e}"
   puts "For detailed error messages, see: #{temp}/error.log"
end

I believe this error is because I am attempting to do something I don't have permission to do, what I don't understand is there a clean way to achieve what I am attempting? Thanks in advance for any time spent on this issue.

I have edited this with my updated code that answers my question. Thanks for all your input.

mrtriangle
  • 542
  • 11
  • 28
  • 2
    You are lacking privileges. Why try to write in `/temp`, why not just `/tmp`? Create a directory somewhere where the user running the script has more privileges, not in root, or use `/tmp`. Or run your script with `sudo`. – Marcin Kołodziej Nov 19 '18 at 05:25
  • 1
    Don't bother specifying the path for a temp directory. Just use `Dir.tmpdir` and/or `Dir.mktmpdir` and let Ruby do the lifting for you: https://ruby-doc.org/stdlib-2.5.3/libdoc/tmpdir/rdoc/Dir.html – anothermh Nov 19 '18 at 05:56

2 Answers2

1

To make it work and compatible with Windows:

require 'logger'
require 'tmpdir'

tmp = Dir.mktmpdir
log = Logger.new File.open(File.join(tmp, 'error.log', 'w')
log.level = Logger::INFO

begin
  # your code here
rescue StandardError => e
  log.error "Error - #{e}"
  puts "For detailed error messages, see the file: /temp/error.log"
end
Dorian
  • 22,759
  • 8
  • 120
  • 116
0
  1. You shouldn't create /tmp directory - this directory always exist.
  2. You should place begin above checking code, not below.
    require 'logger'
    require 'fileutils'

    begin
      log = Logger.new File.open('/tmp/error.log', 'w')
      log.level = Logger::INFO  
    rescue StandardError => e
      puts "Error - #{e}"
    end
Ivan Olshansky
  • 889
  • 2
  • 17
  • 23
  • What about on a windows system? I want to check if a tmp directory exists and if not, create it and write the log file there. – mrtriangle Nov 19 '18 at 05:37
  • 1
    It's `/tmp`, not `/temp` that should exist. Rescuing from opening a file which is supposed to be used for error logging and logging that error to the same file does not make sense. – Marcin Kołodziej Nov 19 '18 at 05:37
  • 2
    @mrtriangle if you're trying to make your program compatible with both Windows and Unix, create your logs somewhere inside your application directory (or handle that in an OS-specific way). – Marcin Kołodziej Nov 19 '18 at 05:38
  • 1
    @mrtriangle, on most Windows system you can't create directory at root level without special permissions. – Ivan Olshansky Nov 19 '18 at 05:41