ruby 如何在Rails7中将“=>Booting Puma”日志设置为JSON格式?(如何在Rails中重写print_boot_information方法?)

pepwfjgg  于 2023-03-08  发布在  Ruby
关注(0)|答案(1)|浏览(59)

我想将以下日志格式化为JSON:

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

Afaik,此行是由以下代码产生的www.example.comhttps://github.com/rails/rails/blob/7c70791470fc517deb7c640bead9f1b47efb5539/railties/lib/rails/commands/server/server_command.rb#L278-L284
提交ID 7c70791 is related to Rails 7.0.4.2,这是我在应用程序中使用的最新版本。
我之所以要将其格式化为JSON,是因为我希望所有生成的日志都是JSON格式,这样应用程序中就不会再有非结构化日志。
我的问题
如何覆盖print_boot_information方法使其显示为JSON?
先谢谢你!
我曾尝试使用以下代码创建文件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

并将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"

(在最后一行添加require_relative "../lib/custom_server_command")。
但这行不通。

7qhs6swi

7qhs6swi1#

看起来您必须稍微更改代码,然后将其添加到config/boot.rb的底部:

require "rails/command" # Allow for base class autoload
require "rails/commands/server/server_command" # Load the ServerCommand class

Rails::Command::ServerCommand.class_eval do
  def print_boot_information(server, url)
    logs = [
      "Booting #{ActiveSupport::Inflector.demodulize(server)}",
      "Rails #{Rails.version} application starting in #{Rails.env} #{url}",
      "Run `bin/rails server --help` for more startup options"
    ]

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

      puts(json_log)
    end
  end
end

相关问题