简体   繁体   English

Ruby:Logger和Daemons

[英]Ruby: Logger and Daemons

i'm using ruby 1.9.2p180 (2011-02-18 revision 30909) 我正在使用ruby 1.9.2p180(2011-02-18修订版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? 任何想法,哪里错了?

The Daemons gem closes all file descriptors when it daemonizes the process. Daemons gem在Daemons关闭所有文件描述符。 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 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. 但请注意,守护进程将工作目录更改为/ ,因此在引用日志文件路径时请将其考虑在内。

A solution which successfully works in delayed_job gem includes extracting all open files before fork, and reopening them later. 在delayed_job gem中成功运行的解决方案包括在fork之前提取所有打开的文件,并在以后重新打开它们。

An adjusted extract from delayed_job : 来自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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM