Class: ElasticGraph::LambdaSupport::JSONAwareLambdaLogFormatter

Inherits:
Logger::Formatter
  • Object
show all
Defined in:
lib/elastic_graph/lambda_support/json_aware_lambda_log_formatter.rb

Overview

A log formatter that supports JSON logging, without requiring all logs to be emitted as JSON.

If the ‘message` is a hash of JSON data, it will produce a JSON-formatted log message combining the standard bits of metadata the AWS Lambda logger already includes in every log message with the passed data.

If it is not a hash of JSON data, it will just delegate to the default formatter used by AWS Lambda.

This is particularly useful to support cloudwatch metric filtering: docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html#metric-filters-extract-json

Constant Summary collapse

FORMAT =
"%<sev>s, [%<datetime>s #%<process>d] %<severity>5s %<request_id>s -- %<progname>s: %<msg>s"

Instance Method Summary collapse

Instance Method Details

#call(severity, time, progname, msg) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/elastic_graph/lambda_support/json_aware_lambda_log_formatter.rb', line 28

def call(severity, time, progname, msg)
   = {
    # These bits of metadata come from the standard AWS Lambda log formatter:
    # https://github.com/aws/aws-lambda-ruby-runtime-interface-client/blob/2.0.0/lib/aws_lambda_ric/lambda_log_formatter.rb#L11-L12
    sev: severity[0..0],
    datetime: format_datetime(time),
    process: $$,
    severity: severity,
    # standard:disable Style/GlobalVars -- don't have a choice here; this is what the AWS Lambda runtime sets.
    request_id: $_global_aws_request_id,
    # standard:enable Style/GlobalVars
    progname: progname
  }

  if msg.is_a?(::Hash)
    ::JSON.generate(msg.merge(), space: " ")
  else
    # See https://github.com/aws/aws-lambda-ruby-runtime-interface-client/blob/2.0.0/lib/aws_lambda_ric/lambda_log_formatter.rb
    (FORMAT % .merge({msg: msg2str(msg)})).encode!("UTF-8")
  end
end