Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Logger and Daemons

i'm using ruby 1.9.2p180 (2011-02-18 revision 30909)

in Order to do the logging i use the logging gem. My program has two blocks, which are used as daemons.

But logging from these blocks results in an error and nothing is written to the logfile:

log shifting failed. closed stream
log writing failed. closed stream

Here is what happens in the code:

log = Logger.new(logbase + 'logfile.log', 'monthly')
log.level = Logger::INFO

proc = Daemons.call(options) do
  # [...]
  log.info "Any Logmessage"
  # [...]
end

Any Idea, whats wrong there?

like image 562
Dakkar Avatar asked Feb 11 '13 08:02

Dakkar


2 Answers

The Daemons gem closes all file descriptors when it daemonizes the process. So any logfiles that were opened before the Daemons block will be closed inside the forked process.

And since you can't write to closed file descriptors -> errors.

You can read more about what happens when you daemonize a process by reading the chapter:

What does daemons internally do with my daemons?
http://daemons.rubyforge.org/Daemons.html

The solution is to open the logfile inside the daemon block instead of outside of it. That should fix it. But note that daemonizing changes the working directory to /, so take that into account when referencing logfile paths.

like image 136
Casper Avatar answered Sep 28 '22 02:09

Casper


A solution which successfully works in delayed_job gem includes extracting all open files before fork, and reopening them later.

An adjusted extract from delayed_job:

@files_to_reopen = []
ObjectSpace.each_object(File) do |file|
  @files_to_reopen << file unless file.closed?
end

Daemons.run_proc('some_process') do
  @files_to_reopen.each do |file|
    file.reopen file.path, 'a+'
    file.sync = true
  end

  # Your code
end
like image 20
knarewski Avatar answered Sep 28 '22 01:09

knarewski