-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathtest_logging.py
More file actions
235 lines (200 loc) · 6.75 KB
/
test_logging.py
File metadata and controls
235 lines (200 loc) · 6.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
import json
import logging
import logging.config
import os
import textwrap
from importlib import reload
import jsonschema
import pytest
from dockerflow.logging import JsonLogFormatter
@pytest.fixture()
def reset_logging():
logging.shutdown()
reload(logging)
logger_name = "tests"
formatter = JsonLogFormatter(logger_name=logger_name)
def assert_records(records):
assert len(records) == 1
details = json.loads(formatter.format(records[0]))
jsonschema.validate(details, JSON_LOGGING_SCHEMA)
return details
def test_initialization_from_ini(reset_logging, caplog, tmpdir):
ini_content = textwrap.dedent(
"""
[loggers]
keys = root
[handlers]
keys = console
[formatters]
keys = json
[logger_root]
level = INFO
handlers = console
[handler_console]
class = StreamHandler
level = DEBUG
args = (sys.stderr,)
formatter = json
[formatter_json]
class = dockerflow.logging.JsonLogFormatter
"""
)
ini_file = tmpdir.join("logging.ini")
ini_file.write(ini_content)
logging.config.fileConfig(str(ini_file))
logging.info("I am logging in mozlog format now! woo hoo!")
logger = logging.getLogger()
assert len(logger.handlers) > 0
assert logger.handlers[0].formatter.logger_name == "Dockerflow"
def test_basic_operation(caplog):
"""Ensure log formatter contains all the expected fields and values"""
message_text = "simple test"
caplog.set_level(logging.DEBUG)
logging.debug(message_text)
details = assert_records(caplog.records)
assert details == formatter.convert_record(caplog.records[0])
assert "Timestamp" in details
assert "Hostname" in details
assert details["Severity"] == 7
assert details["Type"] == "root"
assert details["Pid"] == os.getpid()
assert details["Logger"] == logger_name
assert details["EnvVersion"] == formatter.LOGGING_FORMAT_VERSION
assert details["Fields"]["msg"] == message_text
def test_custom_paramters(caplog):
"""Ensure log formatter can handle custom parameters"""
logger = logging.getLogger("tests.test_logging")
logger.warning("custom test %s", "one", extra={"more": "stuff"})
details = assert_records(caplog.records)
assert details == formatter.convert_record(caplog.records[0])
assert details["Type"] == "tests.test_logging"
assert details["Severity"] == 4
assert details["Fields"]["msg"] == "custom test one"
assert details["Fields"]["more"] == "stuff"
def test_non_json_serializable_parameters_are_converted(caplog):
"""Ensure log formatter doesn't fail with non json-serializable params."""
foo = object()
foo_repr = repr(foo)
logger = logging.getLogger("tests.test_logging")
logger.warning("custom test %s", "hello", extra={"foo": foo})
details = assert_records(caplog.records)
assert details["Type"] == "tests.test_logging"
assert details["Severity"] == 4
assert details["Fields"]["msg"] == "custom test hello"
assert details["Fields"]["foo"] == foo_repr
def test_logging_error_tracebacks(caplog):
"""Ensure log formatter includes exception traceback information"""
try:
raise ValueError("\n")
except Exception:
logging.exception("there was an error")
details = assert_records(caplog.records)
assert details["Severity"] == 3
assert details["Fields"]["msg"] == "there was an error"
assert details["Fields"]["error"].startswith("ValueError('\\n'")
assert details["Fields"]["traceback"].startswith("Uncaught exception:")
assert "ValueError" in details["Fields"]["traceback"]
def test_logging_exc_info_false(caplog):
"""Ensure log formatter does not fail and does not include exception
traceback information when exc_info is False"""
try:
raise ValueError("\n")
except Exception:
logging.exception("there was an error", exc_info=False)
details = assert_records(caplog.records)
assert details["Severity"] == 3
assert details["Fields"]["msg"] == "there was an error"
assert "error" not in details["Fields"]
assert "traceback" not in details["Fields"]
def test_ignore_json_message(caplog):
"""Ensure log formatter ignores messages that are JSON already"""
try:
raise ValueError("\n")
except Exception:
logging.exception(json.dumps({"spam": "eggs"}))
details = assert_records(caplog.records)
assert "msg" not in details["Fields"]
assert formatter.is_value_jsonlike('{"spam": "eggs"}')
assert not formatter.is_value_jsonlike('{"spam": "eggs"')
assert not formatter.is_value_jsonlike('"spam": "eggs"}')
# https://mana.mozilla.org/wiki/pages/viewpage.action?pageId=42895640
JSON_LOGGING_SCHEMA = json.loads(
"""
{
"type":"object",
"required":["Timestamp"],
"properties":{
"Timestamp":{
"type":"integer",
"minimum":0
},
"Type":{
"type":"string"
},
"Logger":{
"type":"string"
},
"Hostname":{
"type":"string",
"format":"hostname"
},
"EnvVersion":{
"type":"string",
"pattern":"^\\d+(?:\\.\\d+){0,2}$"
},
"Severity":{
"type":"integer",
"minimum":0,
"maximum":7
},
"Pid":{
"type":"integer",
"minimum":0
},
"Fields":{
"type":"object",
"minProperties":1,
"additionalProperties":{
"anyOf": [
{ "$ref": "#/definitions/field_value"},
{ "$ref": "#/definitions/field_array"},
{ "$ref": "#/definitions/field_object"}
]
}
}
},
"definitions":{
"field_value":{
"type":["string", "number", "boolean"]
},
"field_array":{
"type":"array",
"minItems": 1,
"oneOf": [
{"items": {"type":"string"}},
{"items": {"type":"number"}},
{"items": {"type":"boolean"}}
]
},
"field_object":{
"type":"object",
"required":["value"],
"properties":{
"value":{
"oneOf": [
{ "$ref": "#/definitions/field_value" },
{ "$ref": "#/definitions/field_array" }
]
},
"representation":{"type":"string"}
}
}
}
}
""".replace(
"\\", "\\\\"
)
) # HACK: Fix escaping for easy copy/paste