generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 34
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
2
commits 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.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,3 +15,4 @@ Gemfile.lock | |
| .ruby-version | ||
| # containerized test runner clone | ||
| .test-runner/ | ||
| .idea/ | ||
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
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')}\n" | ||
|
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. Do we rather want to do 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. To not make bad characters fail @maxday ? |
||
| 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,10 +1,24 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require 'json' | ||
|
|
||
| class LambdaLogger | ||
| class << self | ||
| def log_error(exception:, message: nil) | ||
| puts message if message | ||
| puts JSON.pretty_unparse(exception.to_lambda_response) | ||
| puts formatted_error(exception) | ||
| end | ||
|
|
||
| private | ||
|
|
||
| def formatted_error(exception) | ||
| error_response = exception.to_lambda_response | ||
|
|
||
| if AwsLambdaRIC::TelemetryLogger.telemetry_log_sink.nil? | ||
| JSON.generate(error_response) | ||
| else | ||
| JSON.pretty_unparse(error_response) | ||
| end | ||
| end | ||
| 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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IN this PR I see we are patching both Kernel puts and also logger -> Not this is not usual - For all runtimes we just choose 1 thing and then patch that. For nodejs it's console for python logger. Not sure if we should do both. This is becoming hard to follow. DO we need to patch Kernel.puts?