Write Errors to Log File in Ruby

5k Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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
4
On
  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