【问题标题】:How do I make Rails log timestamps in UTC timezone?如何让 Rails 在 UTC 时区记录时间戳?
【发布时间】:2014-06-23 23:05:12
【问题描述】:

如何让 Rails 以 UTC 而不是本地时间打印日志时间戳?目前正在打印

Started GET "/" for 190.176.185.42 at 2013-08-21 18:27:56 -0400

这将更容易找到用户报告的错误。我看到了这个http://apidock.com/rails/Logger 并尝试了

生产.rb

  Rails.logger.datetime_format = "%Y-%m-%d %H:%M:%S %Z"

但它给出了一个错误

undefined method `datetime_format=' for nil:NilClass (NoMethodError)

我认为仅仅设置格式是行不通的。我想我需要先将时间转换为 UTC。

Rails 3.2.14.

【问题讨论】:

  • 问题是你的记录器是nil。这是为什么呢?
  • 我不知道。它在 production.rb 中。也许它还没有初始化。我应该把那条线放在哪里?这是正确的线路吗?
  • 可能是,试试Rails.logger = ActiveSupport::Logger.new('wherever_the_log_goes.log')

标签: ruby-on-rails ruby ruby-on-rails-3 logging


【解决方案1】:

该行日志是由started_request_message 生成的。似乎很难更改它,因为它被硬编码为使用默认格式。也许您必须根据自己的目的重写此方法。

【讨论】:

    【解决方案2】:

    是的,它成功了!使用 Yanhao 的信息,在 production.rb 的底部,

    Rails::Rack::Logger.class_eval do
      # Override logging to spit out UTC time to easier find user reported errors
      # https://github.com/rails/rails/blob/v3.2.14/railties/lib/rails/rack/logger.rb#L38
      def started_request_message(request)
        'Started %s "%s" for %s at %s' % [
          request.request_method,
          request.filtered_path,
          request.ip,
          Time.now.utc ]
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      • 2019-03-09
      • 2017-06-24
      • 2013-06-30
      相关资源
      最近更新 更多