-
Notifications
You must be signed in to change notification settings - Fork 35
Add structured JSON logging support #58
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,12 +1,69 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require 'json' | ||
| require 'logger' | ||
|
|
||
| class LogFormatter < Logger::Formatter | ||
| FORMAT = '%<sev>s, [%<datetime>s #%<process>d] %<severity>5s %<request_id>s -- %<progname>s: %<msg>s' | ||
|
|
||
| def call(severity, time, progname, msg) | ||
| (FORMAT % {sev: severity[0..0], datetime: format_datetime(time), process: $$, severity: severity, | ||
| request_id: $_global_aws_request_id, progname: progname, msg: msg2str(msg)}).encode!('UTF-8') | ||
| formatted = FORMAT % { | ||
| sev: severity[0..0], | ||
| datetime: format_datetime(time), | ||
| process: $$, | ||
| severity: severity, | ||
| request_id: $_global_aws_request_id, | ||
| progname: progname, | ||
| msg: msg2str(msg) | ||
| } | ||
| "#{formatted.encode('UTF-8', invalid: :replace, undef: :replace, replace: '�')}\n" | ||
| end | ||
| end | ||
|
|
||
| class JsonLogFormatter < Logger::Formatter | ||
| DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%6NZ' | ||
|
|
||
| def call(severity, time, progname, msg) | ||
| payload = { | ||
| timestamp: time.utc.strftime(DATETIME_FORMAT), | ||
| level: severity, | ||
| message: message_for(msg), | ||
| requestId: $_global_aws_request_id | ||
| } | ||
|
|
||
| logger_name = sanitize_utf8(progname) unless progname.nil? | ||
| payload[:logger] = logger_name unless logger_name.nil? || logger_name.empty? | ||
|
|
||
| if msg.is_a?(Exception) | ||
| payload[:errorType] = msg.class.to_s | ||
| payload[:errorMessage] = sanitize_utf8(msg.message) | ||
| payload[:stackTrace] = Array(msg.backtrace).map { |line| sanitize_utf8(line) } | ||
| location = location_for(msg) | ||
| payload[:location] = location unless location.nil? | ||
| end | ||
|
|
||
| "#{JSON.generate(payload.compact)}\n" | ||
| end | ||
|
|
||
| private | ||
|
|
||
| def message_for(msg) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
This could crash the Lambda if user code logs binary data or strings with encoding issues. Why this is Ruby-specific (not needed in let's say Python): Ruby strings are byte buffers with an encoding tag — you can have a string tagged as UTF-8 that contains invalid bytes. The error only surfaces at Python3 for example validates encoding at string creation time ( Suggested fix: With fix: |
||
| result = msg.is_a?(Exception) ? msg.message : msg2str(msg) | ||
| sanitize_utf8(result) | ||
| end | ||
|
|
||
| def location_for(exception) | ||
anzheyazzz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| first_backtrace_line = exception.backtrace&.first | ||
| return nil if first_backtrace_line.nil? | ||
|
|
||
| sanitized_line = sanitize_utf8(first_backtrace_line) | ||
| matched = sanitized_line.match(/\A(?<file>.+):(?<line>\d+):in [`'](?<method>.+)'\z/) | ||
| return "#{matched[:file]}:#{matched[:method]}:#{matched[:line]}" if matched | ||
|
|
||
| sanitized_line | ||
| end | ||
|
|
||
| def sanitize_utf8(value) | ||
| value.to_s.encode('UTF-8', invalid: :replace, undef: :replace, replace: '�') | ||
| end | ||
| end | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,19 +1,57 @@ | ||
| # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
|
|
||
| # frozen_string_literal: true | ||
|
|
||
| require 'logger' | ||
| require_relative 'lambda_log_formatter' | ||
|
|
||
| module LoggerPatch | ||
| def initialize(logdev, shift_age = 0, shift_size = 1048576, level: 'debug', | ||
| progname: nil, formatter: nil, datetime_format: nil, | ||
| binmode: false, shift_period_suffix: '%Y%m%d') | ||
| logdev_lambda_override = logdev | ||
| formatter_override = formatter | ||
| # use unpatched constructor if logdev is a filename or an IO Object other than $stdout or $stderr | ||
| LOG_LEVEL_MAP = { | ||
| 'TRACE' => Logger::DEBUG, | ||
| 'DEBUG' => Logger::DEBUG, | ||
| 'INFO' => Logger::INFO, | ||
| 'WARN' => Logger::WARN, | ||
| 'ERROR' => Logger::ERROR, | ||
| 'FATAL' => Logger::FATAL | ||
| }.freeze | ||
|
|
||
| class << self | ||
| attr_reader :aws_lambda_log_format, :aws_lambda_log_level | ||
|
|
||
| def refresh_runtime_config! | ||
| @aws_lambda_log_format = ENV.fetch('AWS_LAMBDA_LOG_FORMAT', '').upcase | ||
| env_level = ENV.fetch('AWS_LAMBDA_LOG_LEVEL', nil) | ||
| @aws_lambda_log_level = LOG_LEVEL_MAP[env_level&.upcase] | ||
| end | ||
|
|
||
| def json_format? | ||
| @aws_lambda_log_format == 'JSON' | ||
| end | ||
| end | ||
|
|
||
| refresh_runtime_config! | ||
|
|
||
| # shift_size default to 1 megabyte, matching Ruby Logger's default log rotation size. | ||
| def initialize(logdev, shift_age = 0, shift_size = 1_048_576, **kwargs) | ||
anzheyazzz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| level_was_provided = kwargs.key?(:level) | ||
| kwargs = { | ||
| level: Logger::DEBUG, | ||
| progname: nil, | ||
| formatter: nil, | ||
| datetime_format: nil, | ||
| binmode: false, | ||
| shift_period_suffix: '%Y%m%d' | ||
| }.merge(kwargs) | ||
|
|
||
| logdev_override = logdev | ||
|
|
||
| if !logdev || logdev == $stdout || logdev == $stderr | ||
| logdev_lambda_override = AwsLambdaRIC::TelemetryLogger.telemetry_log_sink | ||
| formatter_override = formatter_override || LogFormatter.new | ||
| telemetry_sink = AwsLambdaRIC::TelemetryLogger.telemetry_log_sink | ||
| logdev_override = telemetry_sink || logdev | ||
| kwargs[:formatter] ||= LoggerPatch.json_format? ? JsonLogFormatter.new : LogFormatter.new | ||
| kwargs[:level] = LoggerPatch.aws_lambda_log_level if !level_was_provided && LoggerPatch.aws_lambda_log_level | ||
| end | ||
|
|
||
| super(logdev_lambda_override, shift_age, shift_size, level: level, progname: progname, | ||
| formatter: formatter_override, datetime_format: datetime_format, | ||
| binmode: binmode, shift_period_suffix: shift_period_suffix) | ||
| super(logdev_override, shift_age, shift_size, **kwargs) | ||
| end | ||
| end | ||
Uh oh!
There was an error while loading. Please reload this page.