0
0

More than 1 year has passed since last update.

Railsでログの改行を削除して出力

Posted at

やったこと

SQLなどヒアドキュメントで記述されたテキストが出力されたログが非常に見づらかったので、
改行を削除したログを別途出力するようにした。(ついでに処理時刻とpidも)

コード

config/application.rb
require_relative 'custom_formatter.rb'

class Application < Rails::Application
    config.logger = Logger.new('log/custom.log')
    config.logger.formatter = CustomFormatter.new
    # config.log_formatter = CustomFormatter.new
end
config/custom_formatter.rb
class 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.squish : msg.inspect}\n"
    end
end
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