logdna / ruby

Ruby library for logging to LogDNA
MIT License
17 stars 20 forks source link

Include Rails log_tags in metadata #37

Open willkoehler opened 3 years ago

willkoehler commented 3 years ago

I've made this change locally. But I think it could go in the public gem. I'm using ActiveSupport::TaggedLogging in Rails to include log tags like this:

# This is the default in Rails, but could include more stuff if desired
config.log_tags = [:request_id]

# Send logs to LogDNA
log_dna_logger = Logdna::Ruby.new(
  Rails.application.secrets.log_dna_api_key, {
    env: "development",
    app: "ShayHi",
    level: Logger::DEBUG
  }
)
# Wrap LogDNA logger in TaggedLogging to add log tags
config.logger = ActiveSupport::TaggedLogging.new(log_dna_logger)

I then modified Logdna::Ruby#log to include the tags in the metadata

def log(message = nil, opts = {})
  # MY NEW CODE BELOW vvv
  if formatter.current_tags.present?
    opts[:meta] = (opts[:meta] || {}).merge(tags: formatter.current_tags.join(" "))
  end
  # MY NEW CODE ABOVE ^^^
  if message.nil? && block_given?
    message = yield
  end
  if message.nil?
    @internal_logger.debug("provide either a message or block")
    return
  end
  message = message.to_s.encode("UTF-8")
  @client.write_to_buffer(message, default_opts.merge(opts).merge(
                                     timestamp: (Time.now.to_f * 1000).to_i
                                   ))
end

Logs now look like this:

tags

This is particularly useful for including the Rails request_id in the log metadata. I can open a PR if this is something you're interested in adding to the gem for everyone.

willkoehler commented 3 years ago

For the time being I'm just doing this:

class LogdnaWithTags < Logdna::Ruby
  def log(message = nil, opts = {})
    # add ActiveSupport::TaggedLogging log tags to the metadata
    if formatter.current_tags.present?
      opts[:meta] = (opts[:meta] || {}).merge(tags: formatter.current_tags.join(" "))
    end
    # Call original LogDNA logger
    super
  end
end

And then using as before

# This is the default in Rails, but could include more stuff if desired
config.log_tags = [:request_id]

# Send logs to LogDNA
log_dna_logger = LogdnaWithTags.new(
  Rails.application.secrets.log_dna_api_key, {
    env: "development",
    app: "ShayHi",
    level: Logger::DEBUG
  }
)
# Wrap LogDNA logger in TaggedLogging to add log tags
config.logger = ActiveSupport::TaggedLogging.new(log_dna_logger)