class TaggedLogger

Allow custom tags to be captured

Public Class Methods

new( app, options = {} ) click to toggle source
# File lib/sensible_logging/middlewares/tagged_logger.rb, line 9
def initialize( # rubocop:disable Metrics/MethodLength
  app,
  options = {}
)
  @app = app

  options = {
    logger: Logger.new($stdout),
    tags: [],
    use_default_tags: true,
    tld_length: 1,
    include_log_severity: true
  }.merge(options)

  options[:logger] = setup_severity_tag(options[:logger]) if options[:include_log_severity]

  @logger = ActiveSupport::TaggedLogging.new(options[:logger])
  @tags = []
  @tags += default_tags(tld_length: options[:tld_length]) if options[:use_default_tags]
  @tags += options[:tags]
end

Public Instance Methods

call(env) click to toggle source
# File lib/sensible_logging/middlewares/tagged_logger.rb, line 31
def call(env)
  @logger.tagged(*generate_tags(env)) do |logger|
    env['logger'] = logger
    @app.call(env)
  end
end

Private Instance Methods

default_tags(tld_length: 1) click to toggle source
# File lib/sensible_logging/middlewares/tagged_logger.rb, line 48
def default_tags(tld_length: 1)
  [lambda { |req|
    [subdomain(req.host, tld_length) || 'n/a', ENV['RACK_ENV'], req.env['request_id']]
  }]
end
generate_tags(env) click to toggle source
# File lib/sensible_logging/middlewares/tagged_logger.rb, line 61
def generate_tags(env)
  req = Rack::Request.new(env)
  @tags.map do |tag|
    tag.call(req)
  end
end
setup_severity_tag(logger) click to toggle source
# File lib/sensible_logging/middlewares/tagged_logger.rb, line 40
def setup_severity_tag(logger)
  original_formatter = logger.formatter || ActiveSupport::Logger::SimpleFormatter.new
  logger.formatter = proc do |severity, *args|
    "[#{severity}] #{original_formatter.call(severity, *args)}"
  end
  logger
end
subdomain(host, tld_length) click to toggle source
# File lib/sensible_logging/middlewares/tagged_logger.rb, line 54
def subdomain(host, tld_length)
  IPAddr.new(host)
rescue IPAddr::InvalidAddressError
  subdomain_parser = SubdomainParser.new(tld_length: tld_length)
  subdomain_parser.parse(host)
end