Skip to content

Instantly share code, notes, and snippets.

@juno
Created August 12, 2015 08:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juno/1aea0618ca298fa69bf8 to your computer and use it in GitHub Desktop.
Save juno/1aea0618ca298fa69bf8 to your computer and use it in GitHub Desktop.
Custom log formatter which supprots severity and progname. This works well with Heroku's rails_12factor.gem
# Custom log formatter module for rails_12factor
#
module CustomLogFormatter
# Custom formatter for development environment.
#
# Examples
#
# # in controller
# logger.error(self.class) { 'This is a error message' }
# logger.info { 'This is a info message' }
#
# Output:
#
# 2015/08/10 20:12:05 [ERROR] HomeController -- This is a error message
# 2015/08/10 20:12:05 [INFO ] This is a info message
#
class DevelopmentFormatter < ::Logger::Formatter
include ActiveSupport::TaggedLogging::Formatter
def call(severity, timestamp, progname, msg)
format("%s [%-5s] %s%s\n",
timestamp.strftime('%Y/%m/%d %H:%M:%S'),
severity,
progname ? "#{progname} -- " : nil,
msg)
end
end
# Custom formatter for production environment.
#
# Examples
#
# # in controller
# logger.error(self.class) { 'This is a error message' }
# logger.info { 'This is a info message' }
#
# Output:
#
# [ERROR] HomeController -- This is a error message
# [INFO ] This is a info message
#
class ProductionFormatter < ::Logger::Formatter
include ActiveSupport::TaggedLogging::Formatter
def call(severity, _, progname, msg)
format("[%-5s] %s%s\n",
severity,
progname ? "#{progname} -- " : nil,
msg)
end
end
class Railtie < ::Rails::Railtie
config.after_initialize do
if Rails.env.production?
config.logger.formatter = ProductionFormatter.new
elsif Rails.env.development?
config.logger.formatter = DevelopmentFormatter.new
end
end
end
end
@oehlschl
Copy link

oehlschl commented Mar 21, 2017

Using this same implementation on Rails 4.2.5, I'm getting 'method_missing': undefined method 'logger' for #<Rails::Railtie::Configuration:0x007fbfea686558> (NoMethodError) even after asserting that the before_initialize block from rails_stdout_logging (v0.0.5) runs as expected. Have you ever seen that as well? Thanks in advance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment