Railsでアプリログのフォーマットを変更する方法

Railsでアプリログのフォーマットを変更する方法です。

以下の2ファイルを追加・修正します。

(追加)app/lib/local_dev_log_formatter.rb

1
2
3
4
5
6
7
class LocalDevLogFormatter < ActiveSupport::Logger::SimpleFormatter
def call(severity, timestamp, progname, msg)
formatted_severity = sprintf("%-5s", "#{severity}")
formatted_time = timestamp.strftime("%Y-%m-%d %H:%M:%S.") << timestamp.usec.to_s[0..2].rjust(3)
"[#{formatted_severity} #{formatted_time} ##{Process.pid}] #{msg}\n"
end
end

(修正)config/environments/development.rb

1
2
3
4
5
6
7
8
9
Hoge::Application.configure do

# 中略

config.log_formatter = LocalDevLogFormatter.new # 日時を出力するためにカスタムフォーマッターを指定
logger = ActiveSupport::Logger.new("log/#{Rails.env}.log", 5, 100 * 1024 * 1024)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end

app/lib配下に配置することとconfig.loggerの方にも設定が必要なところが分からなくてハマりました。。

【RSpec】current_companyのメソッドで特定の値を返す

1
2
3
4
before do
company.created_at = Time.local(2022, 12, 02, 0, 0, 0)
allow_any_instance_of(HogeController).to receive(:current_company).and_return(company)
end

いつもモックやスタブではallow(hoge).to receive(:fuga).and_return(piyo)の書き方でやってたので、それがうまく効かなくてハマりました。。

以上です。

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×