LoginSignup
7
7

More than 5 years have passed since last update.

Railsのログにファイル名と行数を表示

Posted at

ログ上にRails.logger.xxx(したと思われる)ファイル名と行数を表示させたら便利なのかと思いました。

方法

config/enviroment.rb
class Logger
  class Formatter
    def call(severity, time, progname, msg)
      file_name, line_num = caller.map { |x| 
        [Pathname.new($1).relative_path_from(Rails.root).to_s, $2] if x =~ /(.*?):(\d+)/
      }.compact.find { |x|
        x[0] !~ /^(..)\//
      }

      file_name ||= ""
      line_num ||= ""

      format = "[%s #%d %s:%s] %5s -- %s: %s\n"
      format % ["#{time.strftime('%g-%m-%d %H:%M:%S.%3N')}",
                  $$, file_name, line_num, severity, progname, msg2str(msg)]
    end
  end
end
config/enviroment/development.rb
config.logger = Logger.new("log/development.log", 'daily')
config.logger.formatter = Logger::Formatter.new 

callerからスタックトレースを取得し、Rails.root配下にあるファイルを発見したらそいつをログに表示します。
スタックトレースを漁るのは重い感じがするけれど、どちらにしろディスクIOの方が遅いから大丈夫。きっと。

結果

こんな感じに出ます。

[13-12-21 23:15:00.705 #5266 app/controllers/hoge_controller.rb:3]  INFO -- : ルイズ!ルイズ!ルイズ!ルイズぅぅうううわぁああああああああああああああああああああああん!!!
[13-12-21 23:15:00.705 #5266 app/controllers/piyopiyo_controller.rb:3]  INFO -- : あぁああああ…ああ…あっあっー!あぁああああああ!!!ルイズルイズルイズぅううぁわぁああああ!!! 

参考

10Logger!!! (ログにタイムスタンプを追加する方法)

7
7
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
7
7