Ruby on RailsでログにタイムスタンプとプロセスIDを表示
やりたいこと
ログ解析のためにタイムスタンプとプロセスIDを表示したい。
方法
タイムスタンプとプロセスIDを表示するためのログフォーマットクラスを定義
$ vi config/environment.rb # Load the rails application require File.expand_path('../application', __FILE__) #「FormatWithTime」という名前で新規ログフォーマットクラスを作成 class Logger::FormatWithTime < Logger::Formatter # 日付フォーマット指定 cattr_accessor(:datetime_format) { "%Y/%m/%d %H:%M:%S" } def call(severity, timestamp, progname, msg) #「$$」は自分のPID "[#{timestamp.strftime(datetime_format)}.#{'%06d' % timestamp.usec.to_s}] (pid=#{$$}) #{severity} -- : #{String === msg ? msg : msg.inspect}\n" end end # Initialize the rails application TimeshiftAnimeLive::Application.initialize!
環境定義ファイルにロガーの設定を追加
$ vi config/environments/development.rb # デフォルトのログのパスを取得してロガー生成 config.logger = Logger.new(config.paths["log"].first) # 新規作成したログフォーマットクラスを指定 config.logger.formatter = Logger::FormatWithTime.new # ログレベルを設定 config.logger.level = Logger::DEBUG
参考サイト
- railsのログへ時刻/PID付与