简体   繁体   English

如何以UTC时区生成Rails日志时间戳?

[英]How do I make Rails log timestamps in UTC timezone?

How do I make Rails print the log timestamps in UTC instead of localtime? 如何使Rails以UTC而不是本地时间打印日志时间戳? It currently prints 它目前打印

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

This will make it easier to find errors reported by users. 这样可以更轻松地查找用户报告的错误。 I saw this http://apidock.com/rails/Logger and tried 我看到了这个http://apidock.com/rails/Logger并试过了

production.rb production.rb

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

but it gave an error 但它给了一个错误

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

I don't think just setting the format will work. 我不认为只是设置格式将起作用。 I think I need to actually convert the time into UTC first. 我想我需要先将时间转换为UTC。

Rails 3.2.14. Rails 3.2.14。

That line of log is generated by started_request_message . 该行日志由started_request_message生成。 It seems hard to change it because it is hard coded to use the default format. 似乎很难改变它,因为硬编码使用默认格式。 Maybe you have to override this method for your purpose. 也许您必须为您的目的覆盖此方法。

Yeah it worked! 是的,它有效! Using Yanhao's info, at the bottom of production.rb, 使用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

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

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