Skip to content

Instantly share code, notes, and snippets.

@katpadi
Last active March 4, 2022 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katpadi/ff2294499307f196cbf5b48fe0064089 to your computer and use it in GitHub Desktop.
Save katpadi/ff2294499307f196cbf5b48fe0064089 to your computer and use it in GitHub Desktop.
UnderscoreLog
# frozen_string_literal: true
# Usage:
# class ServiceX
# include UnderscoreLog
#
# def initialize
# end
#
# def call
# _info { 'WELCOME' }
# _debug { 'TO' }
# _warn { 'THE' }
# _fatal { 'JUNGLE' }
# raise RuntimeError.new
# rescue StandardError => e
# _error('INNER TAG') { "MyPrettyError: #{_pretty_ex(e)}}" }
# end
# end
module UnderscoreLog
def _info(inner_tag = nil)
Rails.logger.tagged([facility, inner_tag].compact) do
Rails.logger.info { yield }
end
end
def _debug(inner_tag = nil)
Rails.logger.tagged([facility, inner_tag].compact) do
Rails.logger.debug { yield }
end
end
def _error(inner_tag = nil)
Rails.logger.tagged([facility, inner_tag].compact) do
Rails.logger.error { yield }
end
end
def _warn(inner_tag = nil)
Rails.logger.tagged([facility, inner_tag].compact) do
Rails.logger.warn { yield }
end
end
def _fatal(inner_tag = nil)
Rails.logger.tagged([facility, inner_tag].compact) do
Rails.logger.fatal { yield }
end
end
def _pretty_ex(exception)
"#{exception.message}\n#{pretty_backtrace(exception)}"
end
private
def pretty_backtrace(exception)
"\tat #{exception.backtrace.join("\n\tat ")}"
end
def facility
@facility ||= self.class.name.gsub(/::/, '.').gsub(/([a-z])([A-Z])/, '\\1_\\2')
end
end
# Result:
# [Service_X] [INFO ] WELCOME
# [Service_X] [DEBUG] TO
# [Service_X] [WARN ] THE
# [Service_X] [FATAL] JUNGLE
# [Service_X] [INNER TAG] [ERROR] MyPrettyError: RuntimeError
# ....
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment