generated from amazon-archives/__template_Apache-2.0
-
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
Open
anzheyazzz
wants to merge
1
commit into
main
Choose a base branch
from
anzhey/structured-logging
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+272
−32
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,12 +1,65 @@ | ||
| # 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 = progname.to_s | ||
| payload[:logger] = logger_name unless logger_name.empty? | ||
|
|
||
| if msg.is_a?(Exception) | ||
| payload[:errorType] = msg.class.to_s | ||
| payload[:errorMessage] = msg.message | ||
| payload[:stackTrace] = msg.backtrace || [] | ||
| location = location_for(msg) | ||
| payload[:location] = location unless location.nil? | ||
| end | ||
|
|
||
| "#{JSON.generate(payload.compact)}\n" | ||
| end | ||
|
|
||
| private | ||
|
|
||
| def message_for(msg) | ||
| return msg.message if msg.is_a?(Exception) | ||
|
|
||
| msg2str(msg) | ||
| end | ||
|
|
||
| def location_for(exception) | ||
| first_backtrace_line = exception.backtrace&.first | ||
| return nil if first_backtrace_line.nil? | ||
|
|
||
| matched = first_backtrace_line.match(/\A(.+):(\d+):in [`'](.+)'\z/) | ||
| return "#{matched[1]}:#{matched[3]}:#{matched[2]}" if matched | ||
|
|
||
| first_backtrace_line | ||
| end | ||
| end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,19 +1,56 @@ | ||
| # 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! | ||
|
|
||
| def initialize(logdev, shift_age = 0, shift_size = 1_048_576, **kwargs) | ||
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require_relative '../../lib/aws_lambda_ric/logger_patch' | ||
| require 'logger' | ||
| require 'stringio' | ||
| require 'minitest/autorun' | ||
|
|
||
| module AwsLambdaRIC | ||
| class TelemetryLogger | ||
| class << self | ||
| attr_accessor :telemetry_log_sink | ||
| end | ||
| end | ||
| end | ||
|
|
||
| class LoggerPatchTest < Minitest::Test | ||
| def setup | ||
| @original_log_format = ENV['AWS_LAMBDA_LOG_FORMAT'] | ||
| @original_log_level = ENV['AWS_LAMBDA_LOG_LEVEL'] | ||
| AwsLambdaRIC::TelemetryLogger.telemetry_log_sink = nil | ||
|
|
||
| @patched_class = Class.new do | ||
| prepend LoggerPatch | ||
| attr_reader :super_args, :super_kwargs | ||
|
|
||
| def initialize(*args, **kwargs) | ||
| @super_args = args | ||
| @super_kwargs = kwargs | ||
| end | ||
| end | ||
| end | ||
|
|
||
| def teardown | ||
| ENV['AWS_LAMBDA_LOG_FORMAT'] = @original_log_format | ||
| ENV['AWS_LAMBDA_LOG_LEVEL'] = @original_log_level | ||
| end | ||
|
|
||
| def test_uses_text_formatter_for_stdout_by_default | ||
| ENV['AWS_LAMBDA_LOG_FORMAT'] = 'TEXT' | ||
| ENV.delete('AWS_LAMBDA_LOG_LEVEL') | ||
| LoggerPatch.refresh_runtime_config! | ||
|
|
||
| instance = @patched_class.new($stdout) | ||
|
|
||
| assert_same $stdout, instance.super_args[0] | ||
| assert_instance_of LogFormatter, instance.super_kwargs[:formatter] | ||
| assert_equal Logger::DEBUG, instance.super_kwargs[:level] | ||
| end | ||
|
|
||
| def test_uses_json_formatter_when_requested | ||
| ENV['AWS_LAMBDA_LOG_FORMAT'] = 'json' | ||
| ENV.delete('AWS_LAMBDA_LOG_LEVEL') | ||
| LoggerPatch.refresh_runtime_config! | ||
|
|
||
| instance = @patched_class.new($stdout) | ||
|
|
||
| assert_instance_of JsonLogFormatter, instance.super_kwargs[:formatter] | ||
| end | ||
|
|
||
| def test_maps_trace_level_to_debug | ||
| ENV['AWS_LAMBDA_LOG_FORMAT'] = 'JSON' | ||
| ENV['AWS_LAMBDA_LOG_LEVEL'] = 'trace' | ||
| LoggerPatch.refresh_runtime_config! | ||
|
|
||
| instance = @patched_class.new($stdout) | ||
|
|
||
| assert_equal Logger::DEBUG, instance.super_kwargs[:level] | ||
| end | ||
|
|
||
| def test_does_not_override_explicit_formatter_or_level | ||
| custom_formatter = Logger::Formatter.new | ||
| ENV['AWS_LAMBDA_LOG_FORMAT'] = 'JSON' | ||
| ENV['AWS_LAMBDA_LOG_LEVEL'] = 'ERROR' | ||
| LoggerPatch.refresh_runtime_config! | ||
|
|
||
| instance = @patched_class.new($stdout, formatter: custom_formatter, level: Logger::WARN) | ||
|
|
||
| assert_same custom_formatter, instance.super_kwargs[:formatter] | ||
| assert_equal Logger::WARN, instance.super_kwargs[:level] | ||
| end | ||
|
|
||
| def test_keeps_custom_logdev_unmodified | ||
| io = StringIO.new | ||
| ENV['AWS_LAMBDA_LOG_FORMAT'] = 'JSON' | ||
| ENV['AWS_LAMBDA_LOG_LEVEL'] = 'ERROR' | ||
| LoggerPatch.refresh_runtime_config! | ||
|
|
||
| instance = @patched_class.new(io) | ||
|
|
||
| assert_same io, instance.super_args[0] | ||
| assert_nil instance.super_kwargs[:formatter] | ||
| assert_equal Logger::DEBUG, instance.super_kwargs[:level] | ||
| end | ||
| end |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.