Search code examples
ruby-on-railsherokuloggingruby-on-rails-5

Approach to a custom rails logger


My Rails application runs in Heroku; recently, we have changed the Heroku LOG_LEVEL to WARN as the system logs flooded with so many unwanted information. But still, in some of the areas, I wanted to use Rails.logger.info;

Currently, in Heroku we have this:

LOG_LEVEL = WARN

And in production.rb, still that is

config.log_level = :info
config.log_formatter = ::Logger::Formatter.new

The above configuration we didn't change it, as the precedence is for LOG_LEVEL if we set that. So with the above configuration, if we put Rails.logger.info "Hello world," that will not work because the logger will only handle the logs equal or higher to warn in importance.

So we have tried one other way.

Created a new initializer called custom_logger.rb; we put

$INFO_LOGGER = Rails.logger.dup
$INFO_LOGGER.level = :info

then wherever we wanted to use info, we just called $INFO_LOGGER.info "Hello World," this prints

Is this a correct approach, like using the global variable?


Solution

  • Is this a correct approach, like using the global variable?

    This question could be considered opinion based, so in my opinion I would not recommend it. Additionally the question posed in the title is regarding a custom logger and while we could implement one to facilitate the request I would propose a simpler solution that will still log exactly what you want, to the current log file, and without the need for a custom logger, a secondary logger, or any kind of global variable.

    My Suggestion:

    Rails uses ActiveSupport::Logger by default which is essentially just a ruby Logger.

    If there are messages you always want logged regardless of the level you can use Logger#unknown.

    Per the Documents for the Logger class:

    Levels:

    UNKNOWN - An unknown message that should always be logged.

    Logger#unknown

    Log an UNKNOWN message. This will be printed no matter what the logger's level is.

    So You can use this to your advantage for the messages that you always want to show while still avoiding the noise of the standard info messages:

    For Example:

    Rails.logger.info "Noisy message" # won't show when LOG_LEVEL > INFO 
    Rails.logger.unknown "VERY IMPORTANT MESSAGE" # will show no matter what the level is set to