如何在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格式,消除非结构化日志。
已尝试的无效方案
- 创建
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"
但上述方案并未生效,启动日志仍为原格式。
问题
如何正确覆写print_boot_information方法,使Rails启动日志输出为JSON格式?
内容的提问来源于stack exchange,提问作者ysf
相关产品推荐
相关产品推荐

