Logging on Rails7

Hi,

I have always used a custom formatter because default rails log formatting is completetly useless and confusing, and I could just write in my {env}.rb

config.log_formatter = My::LogFormatter.new

but starting with Rails 7.1 I am not able anymore to customize the log format, and I cannot find any decent documentation about it. It seems that everything changed, so I am stuck with the useless default format. Log on multiple lines, date and time at the end … real nonsense.

Started GET “/” for 10.90.1.39 at 2024-11-26 11:33:08 +0000 Processing by ApplicationController#status as HTML

etc.

Obviously I’d like to see date and loglevel first, as in any well thought log format.

“[%s] %5s: %s\n” # date loglevel msg

How can I achieve this?

I tried in environment.rb with

Rails.logger.datetime_format = '%Y-%m-%d %H:%M:%S'
Rails.logger.formatter = proc do |severity, datetime, progrname, msg|
  "#{datetime} #{severity} #{msg}\n"
end

but I get this error: undefined method `push_tags’ for #<Proc:0x00000001148514d8 /Users/rd/src/c2/config/environment.rb:9> (NoMethodError)

thanks

Have you considered using lograge or semantic logger?

I don’t need that much complexity, I just need the good old formatter. The only way I found is monkey patching:

module ActiveSupport
  module TaggedLogging
    module Formatter
      def call(severity, timestamp, progname, msg)
        format("[%s] %5s: %s\n", timestamp.strftime('%Y-%m-%dT%H:%M:%S.%3N'), severity, tag_stack.format_message(msg))
      end
    end
  end
end

Any other road was a failure and I find it really weird that such a basic and important feature (decent logging) has been changed completely in v7, making virtually impossibile to customize the logger output. Monkey patch works now, but tomorrow who know …