Rails Log Formatter适用于开发,但不适用于生产

时间:2015-12-02 00:48:04

标签: ruby-on-rails ruby logging production-environment formatter

我通过在每个日志语句中添加时间,用户ID和严重性来使我的Rails记录器更加详细。

我在config / initializers中创建了一个名为log_formatter.rb的新文件来格式化日志消息。这是文件:

class Logger::Formatter
  def call(severity, time, progname, msg)
    "#{Time.now.strftime("%F %T").to_s} #{severity} #{msg}\n"
  end
end

Rails.configuration.log_tags = [
  proc do |req|
    if req.session["warden.user.user.key"].nil?
      "Anonym"
    else
      "uid:#{req.session["warden.user.user.key"][0][0]}"
    end
  end
]

我的config / environments / development.rb包含:

Rails.application.configure do
  config.log_level = :info
  config.log_formatter = Logger::Formatter.new
end

当我处于开发阶段并且输出到日志文件:

时,这非常有效
2015-12-02 00:33:30 INFO [uid:1] <Message>

我的config / environments / production.rb包含:

require_relative './../initializers/log_formatter'
Rails.application.configure do
  config.logger = ActiveSupport::Logger.new(STDOUT)
  config.log_level = :info
  config.log_formatter = Logger::Formatter.new
end

然而,在生产中,我得到的唯一消息来自log_tags

[uid:1] <Message>

我不确定这里有什么改变,但看起来在格式化记录器时没有调用函数'call'。我已经在这个问题上工作了大约一个星期了,我真的很感激你的帮助!

如果您有任何澄清问题,请告诉我,非常感谢!

1 个答案:

答案 0 :(得分:0)

看起来你刚刚得到了一个命名冲突--Roger :: Formatter类包含在Ruby 2.0+中,由于生产中不同的类加载策略,它被加载而不是你的自定义类。只需将您的课程重命名为例如MyLoggerFormatter应该可以工作:

class MyLoggerFormatter
  def call(severity, time, progname, msg)
    "#{Time.now.strftime("%F %T").to_s} #{severity} #{msg}\n"
  end
end

Rails.application.configure do
  config.logger = ActiveSupport::Logger.new(STDOUT)
  config.log_level = :info
  config.log_formatter = MyLoggerFormatter.new
end