【问题标题】:How to prevent Phusion Passenger from overwriting Rails log?如何防止 Phusion 乘客覆盖 Rails 日志?
【发布时间】:2021-10-21 19:54:43
【问题描述】:

我正在使用 nginx 测试乘客,在我的 log/development.log 文件中,看起来每个 SQL 请求都是由乘客触发的:

Decidim::Organization Load (0.3ms)  SELECT  "decidim_organizations".* FROM "decidim_organizations" WHERE "decidim_organizations"."host" = $1 LIMIT $2  [["host", "decidim.domain.tld"], ["LIMIT", 1]]
↳ /usr/lib/ruby/vendor_ruby/phusion_passenger/rack/thread_handler_extension.rb:107

虽然它看起来像预期的行为,但有没有办法将应用程序中的 file:line 添加到堆栈跟踪中?

我想要类似的东西:

Decidim::Organization Load (0.3ms)  SELECT  "decidim_organizations".* FROM "decidim_organizations" WHERE "decidim_organizations"."host" = $1 LIMIT $2  [["host", "decidim.domain.tld"], ["LIMIT", 1]]
↳ /home/user/ror_app/app/models/something.rb:42

添加 config.log_level = :debug 并重新启动服务器没有帮助。

【问题讨论】:

    标签: ruby-on-rails nginx logging passenger


    【解决方案1】:

    你可以add_silencer(忽略)那些包含“phusion_passenger”(或更好:“passenger”)的行到BacktraceCleaner

    # config/initializers/backtrace_silencer.rb
    Rails.backtrace_cleaner.add_silencer { |line| /phusion_passenger/.match?(line) }
    

    更新

    基本上当您将那些passenger 行静音时,它应该显示您的应用程序日志,例如,我假设日志行如下

    Decidim::Organization Load (0.3ms)  SELECT ...
    ↳ /usr/lib/ruby/vendor_ruby/phusion_passenger/rack/thread_handler_extension.rb:107
    ↳ another phusion_passenger
    ↳ /home/user/ror_app/app/models/something.rb:42
    ...
    

    如果您对 phusion_passenger 行静音,则日志应显示 /home/user/ror_app/app/models/something

    看看the log_subscriber code on Rails

    如果中间还有许多其他行,为确保日志将显示应用程序的第一行代码,您可以覆盖上面的 log_subscriber 代码以忽略行,直到到达应用程序中的代码行.

    # your_app/lib/active_record/log_subscriber.rb 
    module ActiveRecord
      class LogSubscriber
        def extract_query_source_location(locations)
          # old code
          # backtrace_cleaner.clean(caller.lazy).first
       
          # new code: to make sure that you log the line of code in your app, 
          # you could replace the regex `/app/` by `/app\/model.../` or
          # whatever you want to reach the code you want to show in logs
          locations.lazy.filter { |line| /app/.match?(line) }.first # first(3)
        end
      end
    end 
    
    # config/initializers/ext_core.rb
    require File.join(Rails.root, "lib", "active_record", "log_subcriber.rb") 
    

    更新

    我认为active-record-query-trace 可以帮助你。

    【讨论】:

    • 感谢您的回答。我真的不想让这些行静音,而是要查看它来自应用程序的哪个文件和行。我发现的唯一方法是在本地运行服务器,但我想知道当堆栈包含外部 Web 服务器(此处为Passenger & nginx)时是否有可能
    • @Sumak 基本上当您使那些客运线路静音时,它应该显示您的应用程序日志。您也可以强制显示您的应用程序的第一行代码,看看我更新的答案。
    • @Sumak 我发现了一颗宝石,我认为它会支持你的情况:github.com/brunofacca/active-record-query-trace
    • 非常感谢!当我有空闲时间时会尝试一下(问题在一个副项目上)。
    猜你喜欢
    • 2011-12-11
    • 2023-02-06
    • 2012-07-24
    • 2012-06-23
    • 2019-09-14
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 2011-04-29
    相关资源
    最近更新 更多