Skip to content

Add default/fallback behavior for json.dumps #47

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

Merged
merged 10 commits into from
Jul 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,14 +1,28 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.2.3
rev: v4.0.1
hooks:
- id: check-case-conflict
- id: check-executables-have-shebangs
- id: check-merge-conflict

- repo: [email protected]:elastic/apm-pipeline-library
rev: current
hooks:
- id: check-bash-syntax
- id: check-jenkins-pipelines
- id: check-jjbb
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.910
hooks:
- id: mypy
args: [--strict]
- repo: https://github.com/ambv/black
rev: 21.6b0
hooks:
- id: black
language_version: python3
- repo: https://gitlab.com/pycqa/flake8
rev: 3.9.2
hooks:
- id: flake8
exclude: tests|conftest.py|setup.py
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* Fixed an issue in `StructlogFormatter` caused by a conflict with `event`
(used for the log `message`) and `event.dataset` (a field provided by the
`elasticapm` integration) ([#46](https://github.com/elastic/ecs-logging-python/pull/46))
* Add default/fallback handling for json.dumps ([#47](https://github.com/elastic/ecs-logging-python/pull/47))

## 1.0.0 (2021-02-08)

Expand Down
28 changes: 25 additions & 3 deletions ecs_logging/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
# under the License.

import json
import functools

try:
import typing
Expand Down Expand Up @@ -152,24 +153,45 @@ def json_dumps(value):
except KeyError:
pass

json_dumps = functools.partial(
json.dumps, sort_keys=True, separators=(",", ":"), default=_json_dumps_fallback
)

# Because we want to use 'sorted_keys=True' we manually build
# the first three keys and then build the rest with json.dumps()
if ordered_fields:
# Need to call json.dumps() on values just in
# case the given values aren't strings (even though
# they should be according to the spec)
ordered_json = ",".join(
'"%s":%s' % (k, json.dumps(v, sort_keys=True, separators=(",", ":")))
'"%s":%s'
% (
k,
json_dumps(v),
)
for k, v in ordered_fields
)
if value:
return "{%s,%s" % (
ordered_json,
json.dumps(value, sort_keys=True, separators=(",", ":"))[1:],
json_dumps(value)[1:],
)
else:
return "{%s}" % ordered_json
# If there are no fields with ordering requirements we
# pass everything into json.dumps()
else:
return json.dumps(value, sort_keys=True, separators=(",", ":"))
return json_dumps(value)


def _json_dumps_fallback(value):
# type: (Any) -> Any
"""
Fallback handler for json.dumps to handle objects json doesn't know how to
serialize.
"""
try:
# This is what structlog's json fallback does
return value.__structlog__()
except AttributeError:
return repr(value)
10 changes: 9 additions & 1 deletion tests/test_structlog_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,18 @@
import pytest


class NotSerializable:
def __repr__(self):
return "<NotSerializable>"


def make_event_dict():
return {
"event": "test message",
"event.dataset": "agent.log",
"log.logger": "logger-name",
"foo": "bar",
"baz": NotSerializable(),
}


Expand All @@ -47,7 +53,9 @@ def test_event_dict_formatted(time, spec_validator):
formatter = ecs_logging.StructlogFormatter()
assert spec_validator(formatter(None, "debug", make_event_dict())) == (
'{"@timestamp":"2020-03-20T16:16:37.187Z","log.level":"debug",'
'"message":"test message","ecs":{"version":"1.6.0"},'
'"message":"test message",'
'"baz":"<NotSerializable>",'
'"ecs":{"version":"1.6.0"},'
'"event":{"dataset":"agent.log"},'
'"foo":"bar",'
'"log":{"logger":"logger-name"}}'
Expand Down