0
0

More than 3 years have passed since last update.

Railsのログ出力をカスタマイズする

Posted at

RailsのログにプロセスIDを出すようにしたかったのでログ出力の変更方法を調べました。

独自フォーマッターの作成

標準ライブラリのフォーマッター(Logger::Formatter)を継承してcallメソッドを上書きします。

log_formatter.rb
class Logger::CustomFormatter < Logger::Formatter
  cattr_accessor(:datetime_format) { "%Y/%m/%d %H:%M:%S" }

  def call(severity, timestamp, _progname, msg)
    "[#{timestamp.strftime(datetime_format)}.#{format('%06d', timestamp.usec)}] (pid=#{$PROCESS_ID}) #{severity} -- : #{msg.class == String ? msg : msg.inspect}\n"
  end
end

今回は通常のログに加えて(pid=#{$PROCESS_ID})を追加しました。
Logger::Formatter

ロガーの設定

Railsのロガーの設定で上記の独自フォーマッターを使うようにします。
下記のように、デフォルトの設定ではなくconfig.loggerに独自のロガーを設定した場合、設定したロガーに直接フォーマッターを設定しないといけないようです。

application.rb
require_relative 'log_formatter.rb'

class Application < Rails::Application
...
config.logger = Logger.new
# config.log_formatter = CustomFormatter.new これは効かない
config.logger.formatter = CustomFormatter.new
...
end

デフォルトのロガーを使う場合はlog_formatterで独自フォーマットが反映されます。

application.rb
require_relative 'log_formatter.rb'

class Application < Rails::Application
...
config.log_formatter = CustomFormatter.new
...
end

サーバーを起動してログを確認してみます。

[2020/08/27 15:04:53.914040] (pid=14046) INFO -- : Completed 200 OK in 531ms (Views: 26.0ms | ActiveRecord: 79.9ms)

プロセスIDがログに出力されました。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0