Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby - can't write to logs in daemons

Normally I can write logs with Logger:

//abc.rb
require 'logger'
logger = Logger.new('foo.log')

$./abc.rb

But in a Daemons I got a permission error:

//xyz.rb
require 'logger'
require 'daemons'

Daemons.run_proc('xyz') do
  logger = Logger.new('foo.log')
end

$./xyz.rb
/home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:599:in `initialize': Permission denied - foo.log (Errno::EACCES)
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:599:in `open'
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:599:in `create_logfile'
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:594:in `open_logfile'
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:549:in `initialize'
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:314:in `new'
from /home/raincole/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/logger.rb:314:in `initialize'

I ran abc.rb and xyz.rb in the same directory and with the same identity. Why can't one log as the other can?

like image 237
Lai Yu-Hsuan Avatar asked Jan 17 '23 06:01

Lai Yu-Hsuan


1 Answers

Here's the reason. From the Daemons documentation.

I have put in bold the relevant part for you:

What does daemons internally do with my daemons?

From a technical aspect of view, daemons does the following when creating a daemon:

  1. Forks a child (and exits the parent process, if needed)
  2. Becomes a session leader (which detaches the program from the controlling terminal).
  3. Forks another child process and exits first child. This prevents the potential of acquiring a controlling terminal.
  4. Changes the current working directory to "/".
  5. Clears the file creation mask (sets umask to 0000).
  6. Closes file descriptors (reopens STDOUT and STDERR to point to a logfile if possible).

So after you start the daemon you should either change your current working directory (Dir.chdir) to the directory you want to use for logging, or use absolute paths for your logfiles.

like image 99
Casper Avatar answered Jan 27 '23 20:01

Casper