-
-
Notifications
You must be signed in to change notification settings - Fork 114
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
Follow upon cloudwatch formatters #138
Closed
terencehonles
wants to merge
4
commits into
kislyuk:develop
from
terencehonles:follow-upon-cloudwatch-formatters
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
f5a5b27
Added CloudWatchFormatter and CloudWatchJSONFormatter classes to hand…
jokerejoker 7dfe420
Added limited example of the CloudWatchJSONFormatter in use with the …
jokerejoker 04261d4
Fixed pre-3.8 non-supported kwargs for logging formatter
jokerejoker f4fb923
make changes backwards compatible
terencehonles 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 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 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 |
---|---|---|
|
@@ -49,6 +49,59 @@ class WatchtowerWarning(UserWarning): | |
pass | ||
|
||
|
||
class CloudWatchFormatter(logging.Formatter): | ||
""" | ||
Log formatter for CloudWatch message. Transforms the logged record message into a compatible message for CloudWatch. | ||
This is the default formatter for CloudWatchLogHandler | ||
|
||
:param json_serialize_default: | ||
The 'default' function to use when serializing dictionaries as JSON. Refer to the Python standard library | ||
documentation on 'json' for more explanation about the 'default' parameter. | ||
https://docs.python.org/3/library/json.html#json.dump | ||
https://docs.python.org/2/library/json.html#json.dump | ||
:type json_serialize_default: Function | ||
""" | ||
|
||
def __init__(self, *args, json_serialize_default=None, **kwargs): | ||
super().__init__(*args, **kwargs) | ||
self.json_serialize_default = json_serialize_default or _json_serialize_default | ||
|
||
def format(self, message): | ||
if isinstance(message.msg, Mapping): | ||
message.msg = json.dumps(message.msg, default=self.json_serialize_default) | ||
|
||
return super().format(message) | ||
|
||
|
||
class CloudWatchJSONFormatter(CloudWatchFormatter): | ||
""" | ||
JSON log formatter for CloudWatch. Transforms the logged record message into a JSON formatted message. | ||
|
||
:param json_serialize_default: | ||
The 'default' function to use when serializing dictionaries as JSON. Refer to the Python standard library | ||
documentation on 'json' for more explanation about the 'default' parameter. | ||
https://docs.python.org/3/library/json.html#json.dump | ||
https://docs.python.org/2/library/json.html#json.dump | ||
:type json_serialize_default: Function | ||
:param fields: A list of fields of the record to include in the CloudWatch Log json object. Defaults to '__all__'. | ||
:type fields: list | ||
""" | ||
def __init__(self, *args, fields='__all__', **kwargs): | ||
super().__init__(*args, **kwargs) | ||
self.fields = fields | ||
|
||
def format(self, message): | ||
if self.fields == '__all__': | ||
message.msg = dict(message.__dict__) | ||
else: | ||
message.msg = {k: v for k, v in message.items() if k in self.fields} | ||
|
||
return super().format(message) | ||
|
||
|
||
_default_formatter = CloudWatchFormatter() | ||
|
||
|
||
class CloudWatchLogHandler(logging.Handler): | ||
""" | ||
Create a new CloudWatch log handler object. This is the main entry point to the functionality of the module. See | ||
|
@@ -91,6 +144,8 @@ class CloudWatchLogHandler(logging.Handler): | |
Create CloudWatch Logs log stream if it does not exist. **True** by default. | ||
:type create_log_stream: Boolean | ||
:param json_serialize_default: | ||
**DEPRECATED**: use CloudWatchFormatter for JSON formatting instead. | ||
|
||
The 'default' function to use when serializing dictionaries as JSON. Refer to the Python standard library | ||
documentation on 'json' for more explanation about the 'default' parameter. | ||
https://docs.python.org/3/library/json.html#json.dump | ||
|
@@ -131,7 +186,6 @@ def __init__(self, log_group=__name__, stream_name=None, use_queues=True, send_i | |
self.stream_name = stream_name | ||
self.use_queues = use_queues | ||
self.send_interval = send_interval | ||
self.json_serialize_default = json_serialize_default or _json_serialize_default | ||
self.max_batch_size = max_batch_size | ||
self.max_batch_count = max_batch_count | ||
self.max_message_size = max_message_size | ||
|
@@ -140,6 +194,12 @@ def __init__(self, log_group=__name__, stream_name=None, use_queues=True, send_i | |
self.creating_log_stream, self.shutting_down = False, False | ||
self.create_log_stream = create_log_stream | ||
self.log_group_retention_days = log_group_retention_days | ||
self.json_serialize_default = json_serialize_default | ||
if json_serialize_default: | ||
warnings.warn( | ||
'Specifying json_serialize_default is deprecated, please create a CloudWatchFormatter instance ' | ||
'which accepts a json_serialize_default and set it as a formatter instead', | ||
DeprecationWarning) | ||
|
||
# Creating session should be the final call in __init__, after all instance attributes are set. | ||
# This ensures that failing to create the session will not result in any missing attribtues. | ||
|
@@ -208,6 +268,19 @@ def _submit_batch(self, batch, stream_name, max_retries=5): | |
# from the response | ||
self.sequence_tokens[stream_name] = response["nextSequenceToken"] | ||
|
||
def format(self, record): | ||
""" | ||
Format the specified record. | ||
|
||
If a formatter is set, use it. Otherwise, use the default formatter for the module. This differs from | ||
`logging.Handler.format` as its default is `CloudWatchFormatter`. | ||
""" | ||
if self.formatter: | ||
fmt = self.formatter | ||
else: | ||
fmt = _default_formatter | ||
return fmt.format(record) | ||
|
||
def emit(self, message): | ||
if self.creating_log_stream: | ||
return # Avoid infinite recursion when asked to log a message as our own side effect | ||
|
@@ -219,7 +292,7 @@ def emit(self, message): | |
if stream_name not in self.sequence_tokens: | ||
self.sequence_tokens[stream_name] = None | ||
|
||
if isinstance(message.msg, Mapping): | ||
if self.json_serialize_default and isinstance(message.msg, Mapping): | ||
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. Dumping JSON will only happen once so it is fine to leave this here instead of removing it. |
||
message.msg = json.dumps(message.msg, default=self.json_serialize_default) | ||
|
||
cwl_message = dict(timestamp=int(message.created * 1000), message=self.format(message)) | ||
|
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.
Please remove the magic value "all" and use None as the placeholder for keeping all field values instead.