Class: SemanticLogger::Appender::NewRelicLogs

Inherits:
Subscriber
  • Object
show all
Defined in:
lib/semantic_logger/appender/new_relic_logs.rb

Constant Summary collapse

CAPTURE_CONTEXT =
lambda do |log|
  meta = ::NewRelic::Agent.
  log.set_context(:new_relic_metadata, meta) unless meta.empty?
end

Instance Attribute Summary

Attributes inherited from Subscriber

#application, #environment, #formatter, #host, #logger, #metrics

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Subscriber

#batch_by_default?, #close, #console_output?, #console_stream, #default_formatter, #flush, #level, #should_log?

Constructor Details

#initialize(formatter: SemanticLogger::Formatters::NewRelicLogs.new, **args, &block) ⇒ NewRelicLogs

Create Appender

Parameters level: [:trace | :debug | :info | :warn | :error | :fatal] Override the log level for this appender. Default: SemanticLogger.default_level

formatter: [Object|Proc]
An instance of a class that implements #call, or a Proc to be used to format
the output from this appender
Default: SemanticLogger::Formatters::NewRelicLogs

filter: [Regexp|Proc]
RegExp: Only include log messages where the class name matches the supplied.
regular expression. All other messages will be ignored.
Proc: Only include log messages where the supplied Proc returns true
      The Proc must return true or false.


48
49
50
51
52
53
54
55
# File 'lib/semantic_logger/appender/new_relic_logs.rb', line 48

def initialize(formatter: SemanticLogger::Formatters::NewRelicLogs.new, **args, &block)
  super

  # Record NewRelic's "trace.id"/"entity.name"/"hostname"/etc, so we can include them later in the formatted output.
  # These are thread-local, so need to be captured as soon as the log-message is created.
  # https://rubydoc.info/gems/newrelic_rpm/NewRelic/Agent#linking_metadata-instance_method
  SemanticLogger.on_log(CAPTURE_CONTEXT)
end

Class Method Details

.log_newrelic(json_message, level) ⇒ Object



73
74
75
# File 'lib/semantic_logger/appender/new_relic_logs.rb', line 73

def self.log_newrelic(json_message, level)
  ::NewRelic::Agent.agent.log_event_aggregator.record(json_message, level)
end

Instance Method Details

#log(log) ⇒ Object

Send an error notification to New Relic



58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/semantic_logger/appender/new_relic_logs.rb', line 58

def log(log)
  begin
    message = formatter.call(log, self) # Generate the structured log
    json_message = Utils.to_json(message) # Convert the log to JSON, repairing any non UTF-8 data
    level = log.level.to_s.upcase # Determine the log level
    self.class.log_newrelic(json_message, level)
  rescue JSON::GeneratorError => e
    warn("Failed to serialize log message to JSON: #{e.message}")
    warn("Problematic data: #{message.inspect}")
  rescue StandardError => e
    warn("Unexpected error while logging to New Relic: #{e.message}")
  end
  true
end