Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Log Formatter works in Development, but not Production

I am making my Rails logger more detailed by adding Time, User ID, and Severity to each log statement.

I created a new file in config/initializers called log_formatter.rb to format the logging messages. Here is the file:

class Logger::Formatter
  def call(severity, time, progname, msg)
    "#{Time.now.strftime("%F %T").to_s} #{severity} #{msg}\n"
  end
end

Rails.configuration.log_tags = [
  proc do |req|
    if req.session["warden.user.user.key"].nil?
      "Anonym"
    else
      "uid:#{req.session["warden.user.user.key"][0][0]}"
    end
  end
]

My config/environments/development.rb contains:

Rails.application.configure do
  config.log_level = :info
  config.log_formatter = Logger::Formatter.new
end

This works perfectly when I am in development and I get an output to the log file of:

2015-12-02 00:33:30 INFO [uid:1] <Message>

My config/environments/production.rb contains:

require_relative './../initializers/log_formatter'
Rails.application.configure do
  config.logger = ActiveSupport::Logger.new(STDOUT)
  config.log_level = :info
  config.log_formatter = Logger::Formatter.new
end

However, while in production, the only message I get is from the log_tags

[uid:1] <Message>

I am not sure what is being changed here, but it looks like the function 'call' is not being called when the logger is being formatted. I have been working on this issue for about a week now, and I would really appreciate the help!

Let me know if you have any clarification questions, and thank you very much!

like image 392
Jeff Avatar asked Dec 06 '25 18:12

Jeff


1 Answers

Looks like you just got a naming clash - Logger::Formatter class is included in Ruby 2.0+, and it got loaded instead of your custom class due to different class loading strategy in production. Just rename your class to e.g. MyLoggerFormatter and it should work:

class MyLoggerFormatter
  def call(severity, time, progname, msg)
    "#{Time.now.strftime("%F %T").to_s} #{severity} #{msg}\n"
  end
end

Rails.application.configure do
  config.logger = ActiveSupport::Logger.new(STDOUT)
  config.log_level = :info
  config.log_formatter = MyLoggerFormatter.new
end
like image 165
Artem Vasiliev Avatar answered Dec 08 '25 07:12

Artem Vasiliev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!