custom loggerを作った
Railsの吐き出すlogとは別に,独自のフォーマットで吐き出してくれるloggerを作りました。
ほとんど、参考サイトのままです。
Railsでcustom log(file)の作り方 – kinopyo blog
カスタマイズしたのは以下の点です。
- タイムスタンプだけでいいのでformat_messageの引数は全部使わず、timestampとmsgのみ使用
- 年度ごとにディレクトリをわけたかったので
Dir.mkdir
でディレクトリがなければ作成。(これがないとエラーが起きます) - ファイル名を日時で動的に作成
ブログ書いているうちに、ログローテーションの記述を書くのを忘れていたことに気づきました。このコードでログローテートならないかも。
# lib/custom_logger.rb class CustomLogger < Logger def format_message(severity, timestamp, progname, msg) "#{timestamp.to_formatted_s(:db)} #{msg}\n" end end path = "#{Rails.root}/log/#{Time.now.strftime('%Y')}" Dir.mkdir(path) unless File.exists?(path) logfile = File.open("#{Rails.root}/log/#{Time.now.strftime('%Y')}/#{Time.now.strftime('%Y-%m-%d')}_log.txt", 'a') logfile.sync = true # automatically flushes data to file CUSTOM_LOGGER = CustomLogger.new(logfile)
コメントを残す