forked from getsentry/sentry-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_logging.py
More file actions
494 lines (376 loc) · 15.7 KB
/
Copy pathtest_logging.py
File metadata and controls
494 lines (376 loc) · 15.7 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
import logging
import warnings
import pytest
from sentry_sdk import get_client
from sentry_sdk.consts import VERSION
from sentry_sdk.integrations.logging import LoggingIntegration, ignore_logger
from tests.test_logs import envelopes_to_logs
other_logger = logging.getLogger("testfoo")
logger = logging.getLogger(__name__)
@pytest.fixture(autouse=True)
def reset_level():
other_logger.setLevel(logging.DEBUG)
logger.setLevel(logging.DEBUG)
@pytest.mark.parametrize("logger", [logger, other_logger])
def test_logging_works_with_many_loggers(sentry_init, capture_events, logger):
sentry_init(integrations=[LoggingIntegration(event_level="ERROR")])
events = capture_events()
logger.info("bread")
logger.critical("LOL")
(event,) = events
assert event["level"] == "fatal"
assert not event["logentry"]["params"]
assert event["logentry"]["message"] == "LOL"
assert event["logentry"]["formatted"] == "LOL"
assert any(crumb["message"] == "bread" for crumb in event["breadcrumbs"]["values"])
@pytest.mark.parametrize("integrations", [None, [], [LoggingIntegration()]])
@pytest.mark.parametrize(
"kwargs", [{"exc_info": None}, {}, {"exc_info": 0}, {"exc_info": False}]
)
def test_logging_defaults(integrations, sentry_init, capture_events, kwargs):
sentry_init(integrations=integrations)
events = capture_events()
logger.info("bread")
logger.critical("LOL", **kwargs)
(event,) = events
assert event["level"] == "fatal"
assert any(crumb["message"] == "bread" for crumb in event["breadcrumbs"]["values"])
assert not any(
crumb["message"] == "LOL" for crumb in event["breadcrumbs"]["values"]
)
assert "threads" not in event
def test_logging_extra_data(sentry_init, capture_events):
sentry_init(integrations=[LoggingIntegration()], default_integrations=False)
events = capture_events()
logger.info("bread", extra=dict(foo=42))
logger.critical("lol", extra=dict(bar=69))
(event,) = events
assert event["level"] == "fatal"
assert event["extra"] == {"bar": 69}
assert any(
crumb["message"] == "bread" and crumb["data"] == {"foo": 42}
for crumb in event["breadcrumbs"]["values"]
)
def test_logging_extra_data_integer_keys(sentry_init, capture_events):
sentry_init(integrations=[LoggingIntegration()], default_integrations=False)
events = capture_events()
logger.critical("integer in extra keys", extra={1: 1})
(event,) = events
assert event["extra"] == {"1": 1}
@pytest.mark.parametrize(
"enable_stack_trace_kwarg",
(
pytest.param({"exc_info": True}, id="exc_info"),
pytest.param({"stack_info": True}, id="stack_info"),
),
)
def test_logging_stack_trace(sentry_init, capture_events, enable_stack_trace_kwarg):
sentry_init(integrations=[LoggingIntegration()], default_integrations=False)
events = capture_events()
logger.error("first", **enable_stack_trace_kwarg)
logger.error("second")
(
event_with,
event_without,
) = events
assert event_with["level"] == "error"
assert event_with["threads"]["values"][0]["stacktrace"]["frames"]
assert event_without["level"] == "error"
assert "threads" not in event_without
def test_logging_level(sentry_init, capture_events):
sentry_init(integrations=[LoggingIntegration()], default_integrations=False)
events = capture_events()
logger.setLevel(logging.WARNING)
logger.error("hi")
(event,) = events
assert event["level"] == "error"
assert event["logentry"]["message"] == "hi"
assert event["logentry"]["formatted"] == "hi"
del events[:]
logger.setLevel(logging.ERROR)
logger.warning("hi")
assert not events
def test_custom_log_level_names(sentry_init, capture_events):
levels = {
logging.DEBUG: "debug",
logging.INFO: "info",
logging.WARN: "warning",
logging.WARNING: "warning",
logging.ERROR: "error",
logging.CRITICAL: "fatal",
logging.FATAL: "fatal",
}
# set custom log level names
logging.addLevelName(logging.DEBUG, "custom level debüg: ")
logging.addLevelName(logging.INFO, "")
logging.addLevelName(logging.WARN, "custom level warn: ")
logging.addLevelName(logging.WARNING, "custom level warning: ")
logging.addLevelName(logging.ERROR, None)
logging.addLevelName(logging.CRITICAL, "custom level critical: ")
logging.addLevelName(logging.FATAL, "custom level 🔥: ")
for logging_level, sentry_level in levels.items():
logger.setLevel(logging_level)
sentry_init(
integrations=[LoggingIntegration(event_level=logging_level)],
default_integrations=False,
)
events = capture_events()
logger.log(logging_level, "Trying level %s", logging_level)
assert events
assert events[0]["level"] == sentry_level
assert events[0]["logentry"]["message"] == "Trying level %s"
assert events[0]["logentry"]["formatted"] == f"Trying level {logging_level}"
assert events[0]["logentry"]["params"] == [logging_level]
del events[:]
def test_logging_filters(sentry_init, capture_events):
sentry_init(integrations=[LoggingIntegration()], default_integrations=False)
events = capture_events()
should_log = False
class MyFilter(logging.Filter):
def filter(self, record):
return should_log
logger.addFilter(MyFilter())
logger.error("hi")
assert not events
should_log = True
logger.error("hi")
(event,) = events
assert event["logentry"]["message"] == "hi"
assert event["logentry"]["formatted"] == "hi"
def test_logging_captured_warnings(sentry_init, capture_events, recwarn):
sentry_init(
integrations=[LoggingIntegration(event_level="WARNING")],
default_integrations=False,
)
events = capture_events()
logging.captureWarnings(True)
warnings.warn("first", stacklevel=2)
warnings.warn("second", stacklevel=2)
logging.captureWarnings(False)
warnings.warn("third", stacklevel=2)
assert len(events) == 2
assert events[0]["level"] == "warning"
# Captured warnings start with the path where the warning was raised
assert "UserWarning: first" in events[0]["logentry"]["message"]
assert "UserWarning: first" in events[0]["logentry"]["formatted"]
# For warnings, the message and formatted message are the same
assert events[0]["logentry"]["message"] == events[0]["logentry"]["formatted"]
assert events[0]["logentry"]["params"] == []
assert events[1]["level"] == "warning"
assert "UserWarning: second" in events[1]["logentry"]["message"]
assert "UserWarning: second" in events[1]["logentry"]["formatted"]
# For warnings, the message and formatted message are the same
assert events[1]["logentry"]["message"] == events[1]["logentry"]["formatted"]
assert events[1]["logentry"]["params"] == []
# Using recwarn suppresses the "third" warning in the test output
assert len(recwarn) == 1
assert str(recwarn[0].message) == "third"
def test_ignore_logger(sentry_init, capture_events):
sentry_init(integrations=[LoggingIntegration()], default_integrations=False)
events = capture_events()
ignore_logger("testfoo")
other_logger.error("hi")
assert not events
def test_ignore_logger_whitespace_padding(sentry_init, capture_events):
"""Here we test insensitivity to whitespace padding of ignored loggers"""
sentry_init(integrations=[LoggingIntegration()], default_integrations=False)
events = capture_events()
ignore_logger("testfoo")
padded_logger = logging.getLogger(" testfoo ")
padded_logger.error("hi")
assert not events
def test_ignore_logger_wildcard(sentry_init, capture_events):
sentry_init(integrations=[LoggingIntegration()], default_integrations=False)
events = capture_events()
ignore_logger("testfoo.*")
nested_logger = logging.getLogger("testfoo.submodule")
logger.error("hi")
nested_logger.error("bye")
(event,) = events
assert event["logentry"]["message"] == "hi"
assert event["logentry"]["formatted"] == "hi"
def test_logging_dictionary_interpolation(sentry_init, capture_events):
"""Here we test an entire dictionary being interpolated into the log message."""
sentry_init(integrations=[LoggingIntegration()], default_integrations=False)
events = capture_events()
logger.error("this is a log with a dictionary %s", {"foo": "bar"})
(event,) = events
assert event["logentry"]["message"] == "this is a log with a dictionary %s"
assert (
event["logentry"]["formatted"]
== "this is a log with a dictionary {'foo': 'bar'}"
)
assert event["logentry"]["params"] == {"foo": "bar"}
def test_logging_dictionary_args(sentry_init, capture_events):
"""Here we test items from a dictionary being interpolated into the log message."""
sentry_init(integrations=[LoggingIntegration()], default_integrations=False)
events = capture_events()
logger.error(
"the value of foo is %(foo)s, and the value of bar is %(bar)s",
{"foo": "bar", "bar": "baz"},
)
(event,) = events
assert (
event["logentry"]["message"]
== "the value of foo is %(foo)s, and the value of bar is %(bar)s"
)
assert (
event["logentry"]["formatted"]
== "the value of foo is bar, and the value of bar is baz"
)
assert event["logentry"]["params"] == {"foo": "bar", "bar": "baz"}
def test_sentry_logs_warning(sentry_init, capture_envelopes):
"""
The python logger module should create 'warn' sentry logs if the flag is on.
"""
sentry_init(_experiments={"enable_logs": True})
envelopes = capture_envelopes()
python_logger = logging.Logger("test-logger")
python_logger.warning("this is %s a template %s", "1", "2")
get_client().flush()
logs = envelopes_to_logs(envelopes)
attrs = logs[0]["attributes"]
assert attrs["sentry.message.template"] == "this is %s a template %s"
assert "code.file.path" in attrs
assert "code.line.number" in attrs
assert attrs["logger.name"] == "test-logger"
assert attrs["sentry.environment"] == "production"
assert attrs["sentry.message.parameter.0"] == "1"
assert attrs["sentry.message.parameter.1"] == "2"
assert attrs["sentry.origin"] == "auto.logger.log"
assert logs[0]["severity_number"] == 13
assert logs[0]["severity_text"] == "warn"
def test_sentry_logs_debug(sentry_init, capture_envelopes):
"""
The python logger module should not create 'debug' sentry logs if the flag is on by default
"""
sentry_init(_experiments={"enable_logs": True})
envelopes = capture_envelopes()
python_logger = logging.Logger("test-logger")
python_logger.debug("this is %s a template %s", "1", "2")
get_client().flush()
assert len(envelopes) == 0
def test_no_log_infinite_loop(sentry_init, capture_envelopes):
"""
If 'debug' mode is true, and you set a low log level in the logging integration, there should be no infinite loops.
"""
sentry_init(
_experiments={"enable_logs": True},
integrations=[LoggingIntegration(sentry_logs_level=logging.DEBUG)],
debug=True,
)
envelopes = capture_envelopes()
python_logger = logging.Logger("test-logger")
python_logger.debug("this is %s a template %s", "1", "2")
get_client().flush()
assert len(envelopes) == 1
def test_logging_errors(sentry_init, capture_envelopes):
"""
The python logger module should be able to log errors without erroring
"""
sentry_init(_experiments={"enable_logs": True})
envelopes = capture_envelopes()
python_logger = logging.Logger("test-logger")
python_logger.error(Exception("test exc 1"))
python_logger.error("error is %s", Exception("test exc 2"))
get_client().flush()
error_event_1 = envelopes[0].items[0].payload.json
assert error_event_1["level"] == "error"
error_event_2 = envelopes[1].items[0].payload.json
assert error_event_2["level"] == "error"
logs = envelopes_to_logs(envelopes)
assert logs[0]["severity_text"] == "error"
assert "sentry.message.template" not in logs[0]["attributes"]
assert "sentry.message.parameter.0" not in logs[0]["attributes"]
assert "code.line.number" in logs[0]["attributes"]
assert logs[1]["severity_text"] == "error"
assert logs[1]["attributes"]["sentry.message.template"] == "error is %s"
assert logs[1]["attributes"]["sentry.message.parameter.0"] in (
"Exception('test exc 2')",
"Exception('test exc 2',)", # py3.6
)
assert "code.line.number" in logs[1]["attributes"]
assert len(logs) == 2
def test_log_strips_project_root(sentry_init, capture_envelopes):
"""
The python logger should strip project roots from the log record path
"""
sentry_init(
_experiments={"enable_logs": True},
project_root="/custom/test",
)
envelopes = capture_envelopes()
python_logger = logging.Logger("test-logger")
python_logger.handle(
logging.LogRecord(
name="test-logger",
level=logging.WARN,
pathname="/custom/test/blah/path.py",
lineno=123,
msg="This is a test log with a custom pathname",
args=(),
exc_info=None,
)
)
get_client().flush()
logs = envelopes_to_logs(envelopes)
assert len(logs) == 1
attrs = logs[0]["attributes"]
assert attrs["code.file.path"] == "blah/path.py"
def test_logger_with_all_attributes(sentry_init, capture_envelopes):
"""
The python logger should be able to log all attributes, including extra data.
"""
sentry_init(_experiments={"enable_logs": True})
envelopes = capture_envelopes()
python_logger = logging.Logger("test-logger")
python_logger.warning(
"log #%d",
1,
extra={"foo": "bar", "numeric": 42, "more_complex": {"nested": "data"}},
)
get_client().flush()
logs = envelopes_to_logs(envelopes)
attributes = logs[0]["attributes"]
assert "process.pid" in attributes
assert isinstance(attributes["process.pid"], int)
del attributes["process.pid"]
assert "sentry.release" in attributes
assert isinstance(attributes["sentry.release"], str)
del attributes["sentry.release"]
assert "server.address" in attributes
assert isinstance(attributes["server.address"], str)
del attributes["server.address"]
assert "thread.id" in attributes
assert isinstance(attributes["thread.id"], int)
del attributes["thread.id"]
assert "code.file.path" in attributes
assert isinstance(attributes["code.file.path"], str)
del attributes["code.file.path"]
assert "code.function.name" in attributes
assert isinstance(attributes["code.function.name"], str)
del attributes["code.function.name"]
assert "code.line.number" in attributes
assert isinstance(attributes["code.line.number"], int)
del attributes["code.line.number"]
assert "process.executable.name" in attributes
assert isinstance(attributes["process.executable.name"], str)
del attributes["process.executable.name"]
assert "thread.name" in attributes
assert isinstance(attributes["thread.name"], str)
del attributes["thread.name"]
assert attributes.pop("sentry.sdk.name").startswith("sentry.python")
# Assert on the remaining non-dynamic attributes.
assert attributes == {
"foo": "bar",
"numeric": 42,
"more_complex": "{'nested': 'data'}",
"logger.name": "test-logger",
"sentry.origin": "auto.logger.log",
"sentry.message.template": "log #%d",
"sentry.message.parameter.0": 1,
"sentry.environment": "production",
"sentry.sdk.version": VERSION,
"sentry.severity_number": 13,
"sentry.severity_text": "warn",
}