Created
August 12, 2015 08:23
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 thebefore_initialize
block fromrails_stdout_logging
(v0.0.5) runs as expected. Have you ever seen that as well? Thanks in advance.