为 Rails 中的每个日志添加会话 ID [英] Add session id to each log in Rails

查看:78
本文介绍了为 Rails 中的每个日志添加会话 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将会话 ID 添加到 Rails 中的每个日志中.

Is there a way to add the session id to each log in Rails.

现在,我已将其添加到我的 environment.rb 中:

Now, I've added this in my environment.rb:

class Logger
  def format_message(severity, timestamp, progname, msg)
    "#{timestamp.to_formatted_s(:db)} #{severity} #{msg}\n" 
  end 
end

首先,这是最佳实践吗?以及如何添加会话 ID?

First of all, is this best-practice? And how do I add the session id?

推荐答案

当您使用 rails 3.2 时,您可以使用日志标签:

when you are working with rails 3.2 you can use log tags:

更新 Rails::Rack::Logger 中间件以应用在config.log_tags 到新的 ActiveSupport::TaggedLoggingRails.logger.这使得使用调试标记日志行变得容易子域和请求 id 等信息——两者都非常有帮助调试多用户生产应用程序 DHH

Update Rails::Rack::Logger middleware to apply any tags set in config.log_tags to the newly ActiveSupport::TaggedLogging Rails.logger. This makes it easy to tag log lines with debug information like subdomain and request id -- both very helpful in debugging multi-user production applications DHH

运气好的话,将它添加到您的环境中可能会奏效:

with some luck, adding this to your environment might work:

config.log_tags = [:uuid, :remote_ip, :session_id]

更新

不幸的是,解决方案来自@shigeya的回答.

for the unlucky, the solution is from the answer of @shigeya.

不幸的是,rails 没有提供一种以理智的方式访问您的 sessionid 的方法.您总是必须依赖于机架在其内部执行的操作...使用您的 cookie 密钥访问 cookie_jar 是推荐"这样做的方式.

unfortunately rails does NOT provide a way to access your sessionid in a sane manner. you always have to rely on what rack is doing in it's internals... accessing the cookie_jar with your cookie key is the "recommended" way of doing so.

这是我在我的应用程序中使用的:

this is what i use for my application:

config.log_tags = [
  :host,
  :remote_ip,
  lambda { |request| "#{request.uuid}"[0..15] },
  lambda { |request| "#{request.cookie_jar["_session_id"]}"[0..15] },
]

输出如下所示:

[hamburg.onruby.dev] [127.0.0.1] [27666d0897c88b32] [BAh7B0kiD3Nlc3Np] Completed 200 OK in 298ms (Views: 286.2ms | ActiveRecord: 9.2ms)

这篇关于为 Rails 中的每个日志添加会话 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆