You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rails 7中将Booting Puma日志转为JSON并覆写print_boot_information方法

如何覆写Rails的print_boot_information方法输出JSON格式启动日志

需求背景

我希望将Rails默认的非结构化启动日志转为JSON格式,原启动日志如下:

=> Booting Puma
=> Rails 7.0.4.2 application starting in development
=> Run `bin/rails server --help` for more startup options

这些日志由Rails 7.0.4.2版本中railties/lib/rails/commands/server/server_command.rb文件的print_boot_information方法生成。我的目标是让应用所有日志都采用结构化JSON格式,消除非结构化日志。

已尝试的无效方案

  1. 创建lib/custom_server_command.rb文件,代码如下:
require "rails/commands"

module Rails
  module Command
      class ServerCommand < Base
        def print_boot_information
          logs = [
            "Booting #{ActiveSupport::Inflector.demodulize(server)}",
            "Rails #{Rails.version} application starting in #{Rails.env} #{url}",
            "Run `#{executable} --help` for more startup options"
          ]

          logs.each do |log|
            json_log = {
              msg: log,
            }.to_json

            puts(json_log)
          end
        end
      end
  end
end
  1. 修改bin/rails文件,在末尾引入自定义文件:
#!/usr/bin/env ruby
APP_PATH = File.expand_path("../config/application", __dir__)
require_relative "../config/boot"
require "rails/commands"
require_relative "../lib/custom_server_command"

但上述方案并未生效,启动日志仍为原格式。

问题

如何正确覆写print_boot_information方法,使Rails启动日志输出为JSON格式?


内容的提问来源于stack exchange,提问作者ysf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 04:35:24