9

如何让我的 Rails 应用程序的每个独角兽工作者写入不同的日志文件?

为什么:混合日志文件的问题...在其默认配置中,Rails 会将其日志消息写入单个日志文件:log/<environment>.log.

独角兽工人将立即写入同一个日志文件,消息可能会混淆。这是 request-log-analyzer 解析日志文件时的问题。一个例子:

Processing Controller1#action1 ...
Processing Controller2#action2 ...
Completed in 100ms...
Completed in 567ms...

在这个例子中,什么动作在 100 毫秒内完成,什么动作在 567 毫秒内完成?我们永远无法确定。

4

2 回答 2

3

将此代码添加到 unicorn.rb 中的 after_fork 中:

#one log per unicorn worker
if log = Rails.logger.instance_values['log']
  ext = File.extname log.path
  new_path =log.path.gsub %r{(.*)(#{Regexp.escape ext})}, "\\1.#{worker.nr}\\2"
  Rails.logger.instance_eval do
    @log.close
    @log= open_log new_path, 'a+'
  end
end
于 2011-10-16T07:20:47.293 回答
2

@slact 的答案在 Rails 3 上不起作用。这有效

after_fork do |server, worker|

  # Override the default logger to use a separate log for each Unicorn worker.
  # https://github.com/rails/rails/blob/3-2-stable/railties/lib/rails/application/bootstrap.rb#L23-L49
  Rails.logger = ActiveRecord::Base.logger = ActionController::Base.logger = begin
    path = Rails.configuration.paths["log"].first
    f = File.open(path.sub(".log", "-#{worker.nr}.log"), "a")
    f.binmode
    f.sync = true
    logger = ActiveSupport::TaggedLogging.new(ActiveSupport::BufferedLogger.new(f))
    logger.level = ActiveSupport::BufferedLogger.const_get(Rails.configuration.log_level.to_s.upcase)
    logger
  end
end
于 2013-09-25T20:08:21.403 回答