-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathtest_logging.py
More file actions
2293 lines (1863 loc) · 73.9 KB
/
test_logging.py
File metadata and controls
2293 lines (1863 loc) · 73.9 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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import json
import logging
import sys
import time
import uuid
from contextlib import nullcontext
from datetime import datetime
from functools import partial
from io import StringIO
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Generator
from unittest import mock
from unittest.mock import ANY, AsyncMock, MagicMock, patch
import pytest
from rich.color import Color, ColorType
from rich.console import Console
from rich.highlighter import NullHighlighter, ReprHighlighter
from rich.style import Style
from websockets.asyncio.client import ClientConnection
import prefect
import prefect.logging.configuration
import prefect.settings
from prefect import flow, task
from prefect._internal.concurrency.api import create_call, from_sync
from prefect.client.orchestration import PrefectClient
from prefect.client.schemas.filters import LogFilter, LogFilterFlowRunId
from prefect.context import FlowRunContext, TaskRunContext
from prefect.exceptions import MissingContextError
from prefect.logging import LogEavesdropper
from prefect.logging.configuration import (
DEFAULT_LOGGING_SETTINGS_PATH,
ensure_logging_setup,
load_logging_config,
setup_logging,
)
from prefect.logging.filters import ObfuscateApiKeyFilter
from prefect.logging.formatters import JsonFormatter
from prefect.logging.handlers import (
APILogHandler,
APILogWorker,
PrefectConsoleHandler,
WorkerAPILogHandler,
_SafeStreamHandler,
emit_api_log,
set_api_log_sink,
)
from prefect.logging.highlighters import PrefectConsoleHighlighter
from prefect.logging.loggers import (
PrefectLogAdapter,
disable_logger,
disable_run_logger,
flow_run_logger,
get_logger,
get_run_logger,
get_worker_logger,
patch_print,
task_run_logger,
)
from prefect.server.schemas.actions import LogCreate
from prefect.settings import (
PREFECT_API_KEY,
PREFECT_API_URL,
PREFECT_CLOUD_MAX_LOG_SIZE,
PREFECT_LOGGING_COLORS,
PREFECT_LOGGING_EXTRA_LOGGERS,
PREFECT_LOGGING_LEVEL,
PREFECT_LOGGING_MARKUP,
PREFECT_LOGGING_SETTINGS_PATH,
PREFECT_LOGGING_TO_API_BATCH_INTERVAL,
PREFECT_LOGGING_TO_API_BATCH_SIZE,
PREFECT_LOGGING_TO_API_ENABLED,
PREFECT_LOGGING_TO_API_MAX_LOG_SIZE,
PREFECT_LOGGING_TO_API_WHEN_MISSING_FLOW,
PREFECT_SERVER_LOGGING_LEVEL,
PREFECT_TEST_MODE,
temporary_settings,
)
from prefect.testing.cli import temporary_console_width
from prefect.types._datetime import from_timestamp, now
from prefect.utilities.names import obfuscate
from prefect.workers.base import BaseJobConfiguration, BaseWorker
if TYPE_CHECKING:
from prefect.client.schemas.objects import FlowRun, TaskRun
from prefect.server.events.pipeline import EventsPipeline
def _normalize_timestamp(timestamp: str) -> str:
if timestamp.endswith("Z"):
if "." in timestamp:
base, frac = timestamp[:-1].split(".")
# Normalize fractional seconds to 6 digits
frac = (frac + "000000")[:6]
timestamp = f"{base}.{frac}+00:00"
else:
timestamp = timestamp[:-1] + "+00:00"
return timestamp
@pytest.fixture
def dictConfigMock(monkeypatch: pytest.MonkeyPatch):
mock = MagicMock()
monkeypatch.setattr("logging.config.dictConfig", mock)
# Reset the process global since we're testing `setup_logging`
old = prefect.logging.configuration.PROCESS_LOGGING_CONFIG
prefect.logging.configuration.PROCESS_LOGGING_CONFIG = {}
yield mock
prefect.logging.configuration.PROCESS_LOGGING_CONFIG = old
@pytest.fixture
async def logger_test_deployment(prefect_client: PrefectClient):
"""
A deployment with a flow that returns information about the given loggers
"""
@prefect.flow
def my_flow() -> dict[str, Any]:
import logging
settings: dict[str, Any] = {}
for logger_name in ["foo", "bar", "prefect"]:
logger = logging.getLogger(logger_name)
settings[logger_name] = {
"handlers": [handler.name for handler in logger.handlers],
"level": logger.level,
}
logger.info(f"Hello from {logger_name}")
return settings
flow_id = await prefect_client.create_flow(my_flow)
deployment_id = await prefect_client.create_deployment(
flow_id=flow_id,
name="logger_test_deployment",
)
return deployment_id
def test_setup_logging_uses_default_path(tmp_path: Path, dictConfigMock: MagicMock):
with temporary_settings(
{PREFECT_LOGGING_SETTINGS_PATH: tmp_path.joinpath("does-not-exist.yaml")}
):
expected_config = load_logging_config(DEFAULT_LOGGING_SETTINGS_PATH)
expected_config["incremental"] = False
setup_logging()
dictConfigMock.assert_called_once_with(expected_config)
def test_setup_logging_sets_incremental_on_repeated_calls(dictConfigMock: MagicMock):
setup_logging()
assert dictConfigMock.call_count == 1
setup_logging()
assert dictConfigMock.call_count == 2
assert dictConfigMock.mock_calls[0][1][0]["incremental"] is False
assert dictConfigMock.mock_calls[1][1][0]["incremental"] is True
def test_setup_logging_uses_settings_path_if_exists(
tmp_path: Path, dictConfigMock: MagicMock
):
config_file = tmp_path.joinpath("exists.yaml")
config_file.write_text("foo: bar")
with temporary_settings({PREFECT_LOGGING_SETTINGS_PATH: config_file}):
setup_logging()
expected_config = load_logging_config(tmp_path.joinpath("exists.yaml"))
expected_config["incremental"] = False
dictConfigMock.assert_called_once_with(expected_config)
def test_setup_logging_uses_env_var_overrides(
tmp_path: Path, dictConfigMock: MagicMock, monkeypatch: pytest.MonkeyPatch
):
with temporary_settings(
{PREFECT_LOGGING_SETTINGS_PATH: tmp_path.joinpath("does-not-exist.yaml")}
):
expected_config = load_logging_config(DEFAULT_LOGGING_SETTINGS_PATH)
env: dict[str, Any] = {}
expected_config["incremental"] = False
# Test setting a value for a simple key
env["PREFECT_LOGGING_HANDLERS_API_LEVEL"] = "API_LEVEL_VAL"
expected_config["handlers"]["api"]["level"] = "API_LEVEL_VAL"
# Test setting a value for the root logger
env["PREFECT_LOGGING_ROOT_LEVEL"] = "ROOT_LEVEL_VAL"
expected_config["root"]["level"] = "ROOT_LEVEL_VAL"
# Test setting a single list value
env["PREFECT_LOGGING_ROOT_HANDLERS"] = "ROOT_HANDLERS_SINGLE_VAL"
expected_config["root"]["handlers"] = ["ROOT_HANDLERS_SINGLE_VAL"]
# Test setting a multi list value
env["PREFECT_LOGGING_ROOT_HANDLERS"] = (
"ROOT_HANDLERS_FIRST_VAL,ROOT_HANDLERS_SECOND_VAL"
)
expected_config["root"]["handlers"] = [
"ROOT_HANDLERS_FIRST_VAL",
"ROOT_HANDLERS_SECOND_VAL",
]
# Test setting a value where the a key contains underscores
env["PREFECT_LOGGING_FORMATTERS_STANDARD_FLOW_RUN_FMT"] = "UNDERSCORE_KEY_VAL"
expected_config["formatters"]["standard"]["flow_run_fmt"] = "UNDERSCORE_KEY_VAL"
# Test setting a value where the key contains a period
env["PREFECT_LOGGING_LOGGERS_PREFECT_EXTRA_LEVEL"] = "VAL"
expected_config["loggers"]["prefect.extra"]["level"] = "VAL"
# Test setting a value that does not exist in the yaml config and should not be
# set in the expected_config since there is no value to override
env["PREFECT_LOGGING_FOO"] = "IGNORED"
for var, value in env.items():
monkeypatch.setenv(var, value)
with temporary_settings(
{PREFECT_LOGGING_SETTINGS_PATH: tmp_path.joinpath("does-not-exist.yaml")}
):
setup_logging()
dictConfigMock.assert_called_once_with(expected_config)
def test_setup_logging_preserves_existing_root_logger_configuration(
dictConfigMock: MagicMock,
):
"""
Test that setup_logging does not override the root logger configuration
if the user has already configured it.
This addresses issue #18872 where importing Prefect would overwrite
user-defined logging formats and handlers.
"""
import logging
# Simulate user configuring the root logger before importing Prefect
root_logger = logging.getLogger()
handler = MagicMock()
root_logger.handlers = [handler]
# Run setup_logging (normally happens on import)
setup_logging()
# The config passed to dictConfig should not have a 'root' key
# since we detected existing root logger configuration
called_config = dictConfigMock.call_args[0][0]
assert "root" not in called_config
# Clean up
root_logger.handlers = []
def test_setup_logging_applies_root_config_when_no_prior_configuration(
dictConfigMock: MagicMock,
):
"""
Test that setup_logging applies the root logger configuration
when the user hasn't configured logging beforehand.
"""
import logging
# Ensure root logger has no handlers (fresh state)
root_logger = logging.getLogger()
root_logger.handlers = []
# Run setup_logging
setup_logging()
# The config should include root logger configuration
called_config = dictConfigMock.call_args[0][0]
assert "root" in called_config
assert called_config["root"]["level"] == "WARNING"
assert called_config["root"]["handlers"] == ["console"]
def test_ensure_logging_setup_calls_setup_logging_when_not_configured(
dictConfigMock: MagicMock,
):
ensure_logging_setup()
dictConfigMock.assert_called_once()
def test_ensure_logging_setup_is_idempotent(dictConfigMock: MagicMock):
ensure_logging_setup()
ensure_logging_setup()
ensure_logging_setup()
# setup_logging should only be called once since PROCESS_LOGGING_CONFIG
# is populated after the first call
dictConfigMock.assert_called_once()
def test_setting_aliases_respected_for_logging_config(tmp_path: Path):
logging_config_content = """
loggers:
prefect:
level: "${PREFECT_LOGGING_SERVER_LEVEL}"
"""
config_file = tmp_path / "logging.yaml"
config_file.write_text(logging_config_content)
with temporary_settings(
{
PREFECT_LOGGING_SETTINGS_PATH: config_file,
PREFECT_SERVER_LOGGING_LEVEL: "INFO",
}
):
config = setup_logging()
assert config["loggers"]["prefect"]["level"] == "INFO"
@pytest.mark.parametrize("name", ["default", None, ""])
def test_get_logger_returns_prefect_logger_by_default(name: str | None):
if name == "default":
logger = get_logger()
else:
logger = get_logger(name)
assert logger.name == "prefect"
def test_get_logger_returns_prefect_child_logger():
logger = get_logger("foo")
assert logger.name == "prefect.foo"
def test_get_logger_does_not_duplicate_prefect_prefix():
logger = get_logger("prefect.foo")
assert logger.name == "prefect.foo"
def test_default_level_is_applied_to_interpolated_yaml_values(
dictConfigMock: MagicMock,
):
with temporary_settings(
{PREFECT_LOGGING_LEVEL: "WARNING", PREFECT_TEST_MODE: False}
):
expected_config = load_logging_config(DEFAULT_LOGGING_SETTINGS_PATH)
expected_config["incremental"] = False
assert expected_config["loggers"]["prefect"]["level"] == "WARNING"
assert expected_config["loggers"]["prefect.extra"]["level"] == "WARNING"
setup_logging()
dictConfigMock.assert_called_once_with(expected_config)
@pytest.fixture()
def external_logger_setup(request: pytest.FixtureRequest):
# This fixture will create a logger with the specified name, level, and propagate value
name, level = request.param
logger = logging.getLogger(name)
old_level, old_propagate = logger.level, logger.propagate
assert logger.level == logging.NOTSET, "Logger should start with NOTSET level"
assert logger.handlers == [], "Logger should start with no handlers"
logger.setLevel(level)
yield name, level, old_propagate
# Reset the logger to its original state
logger.setLevel(old_level)
logger.propagate = old_propagate
logger.handlers = []
@pytest.mark.parametrize(
"external_logger_setup",
[
("foo", logging.DEBUG),
("foo.child", logging.DEBUG),
("foo", logging.INFO),
("foo.child", logging.INFO),
("foo", logging.WARNING),
("foo.child", logging.WARNING),
("foo", logging.ERROR),
("foo.child", logging.ERROR),
("foo", logging.CRITICAL),
("foo.child", logging.CRITICAL),
],
indirect=True,
ids=lambda x: f"logger='{x[0]}'-level='{logging._levelToName[x[1]]}'", # type: ignore[reportPrivateUsage]
)
def test_setup_logging_extra_loggers_does_not_modify_external_logger_level(
dictConfigMock: MagicMock, external_logger_setup: tuple[str, int, bool]
):
ext_name, ext_level, ext_propagate = external_logger_setup
with temporary_settings(
{
PREFECT_LOGGING_LEVEL: "WARNING",
PREFECT_TEST_MODE: False,
PREFECT_LOGGING_EXTRA_LOGGERS: ext_name,
}
):
expected_config = load_logging_config(DEFAULT_LOGGING_SETTINGS_PATH)
expected_config["incremental"] = False
setup_logging()
dictConfigMock.assert_called_once_with(expected_config)
external_logger = logging.getLogger(ext_name)
assert external_logger.level == ext_level, "External logger level was not preserved"
if ext_level > logging.NOTSET:
assert external_logger.isEnabledFor(ext_level), (
"External effective level was not preserved"
)
assert external_logger.propagate == ext_propagate, (
"External logger propagate was not preserved"
)
@pytest.fixture
def mock_log_worker(monkeypatch: pytest.MonkeyPatch):
mock = MagicMock()
monkeypatch.setattr("prefect.logging.handlers.APILogWorker", mock)
return mock
@pytest.mark.enable_api_log_handler
class TestAPILogHandler:
@pytest.fixture
def handler(self) -> Generator[APILogHandler, None, None]:
yield APILogHandler()
@pytest.fixture
def logger(self, handler: APILogHandler):
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
yield logger
logger.removeHandler(handler)
def test_worker_is_not_flushed_on_handler_close(self, mock_log_worker: MagicMock):
handler = APILogHandler()
handler.close()
mock_log_worker.drain_all.assert_not_called()
async def test_logs_can_still_be_sent_after_close(
self,
logger: logging.Logger,
handler: APILogHandler,
flow_run: "FlowRun",
prefect_client: PrefectClient,
):
logger.info("Test", extra={"flow_run_id": flow_run.id})
handler.close() # Close it
logger.info("Test", extra={"flow_run_id": flow_run.id})
await handler.aflush()
log_filter = LogFilter(flow_run_id=LogFilterFlowRunId(any_=[flow_run.id]))
logs = await prefect_client.read_logs(log_filter=log_filter)
assert len(logs) == 2
async def test_logs_can_still_be_sent_after_flush(
self,
logger: logging.Logger,
handler: APILogHandler,
flow_run: "FlowRun",
prefect_client: PrefectClient,
):
logger.info("Test", extra={"flow_run_id": flow_run.id})
await handler.aflush()
logger.info("Test", extra={"flow_run_id": flow_run.id})
await handler.aflush()
log_filter = LogFilter(flow_run_id=LogFilterFlowRunId(any_=[flow_run.id]))
logs = await prefect_client.read_logs(log_filter=log_filter)
assert len(logs) == 2
async def test_sync_flush_from_async_context(
self,
logger: logging.Logger,
handler: APILogHandler,
flow_run: "FlowRun",
prefect_client: PrefectClient,
):
logger.info("Test", extra={"flow_run_id": flow_run.id})
handler.flush()
# Yield to the worker thread
time.sleep(2)
log_filter = LogFilter(flow_run_id=LogFilterFlowRunId(any_=[flow_run.id]))
logs = await prefect_client.read_logs(log_filter=log_filter)
assert len(logs) == 1
def test_sync_flush_from_global_event_loop(
self, logger: logging.Logger, handler: APILogHandler, flow_run: "FlowRun"
):
logger.info("Test", extra={"flow_run_id": flow_run.id})
with pytest.raises(RuntimeError, match="would block"):
from_sync.call_soon_in_loop_thread(create_call(handler.flush)).result()
def test_sync_flush_from_sync_context(
self, logger: logging.Logger, handler: APILogHandler, flow_run: "FlowRun"
):
logger.info("Test", extra={"flow_run_id": flow_run.id})
handler.flush()
def test_sends_task_run_log_to_worker(
self, logger: logging.Logger, mock_log_worker: MagicMock, task_run: "TaskRun"
):
with TaskRunContext.model_construct(task_run=task_run):
logger.info("test-task")
expected = LogCreate.model_construct(
flow_run_id=task_run.flow_run_id,
task_run_id=task_run.id,
name=logger.name,
level=logging.INFO,
message="test-task",
).model_dump(mode="json")
expected["timestamp"] = ANY # Tested separately
expected["__payload_size__"] = ANY # Tested separately
mock_log_worker.instance().send.assert_called_once_with(expected)
def test_sends_flow_run_log_to_worker(
self, logger: logging.Logger, mock_log_worker: MagicMock, flow_run: "FlowRun"
):
with FlowRunContext.model_construct(flow_run=flow_run):
logger.info("test-flow")
expected = LogCreate.model_construct(
flow_run_id=flow_run.id,
task_run_id=None,
name=logger.name,
level=logging.INFO,
message="test-flow",
).model_dump(mode="json")
expected["timestamp"] = ANY # Tested separately
expected["__payload_size__"] = ANY # Tested separately
mock_log_worker.instance().send.assert_called_once_with(expected)
def test_sends_log_to_overridden_sink(
self,
logger: logging.Logger,
mock_log_worker: MagicMock,
flow_run: "FlowRun",
):
log_sink = MagicMock()
set_api_log_sink(log_sink)
try:
with FlowRunContext.model_construct(flow_run=flow_run):
logger.info("test-flow")
finally:
set_api_log_sink(None)
log_sink.assert_called_once()
mock_log_worker.instance().send.assert_not_called()
def test_emit_api_log_sends_to_worker_without_override(
self, mock_log_worker: MagicMock
):
set_api_log_sink(None)
payload = {"message": "test-api-log"}
emit_api_log(payload)
mock_log_worker.instance().send.assert_called_once_with(payload)
@pytest.mark.parametrize("with_context", [True, False])
def test_respects_explicit_flow_run_id(
self,
logger: logging.Logger,
mock_log_worker: MagicMock,
flow_run: "FlowRun",
with_context: bool,
):
flow_run_id = uuid.uuid4()
context = (
FlowRunContext.model_construct(flow_run=flow_run)
if with_context
else nullcontext()
)
with context:
logger.info("test-task", extra={"flow_run_id": flow_run_id})
expected = LogCreate.model_construct(
flow_run_id=flow_run_id,
task_run_id=None,
name=logger.name,
level=logging.INFO,
message="test-task",
).model_dump(mode="json")
expected["timestamp"] = ANY # Tested separately
expected["__payload_size__"] = ANY # Tested separately
mock_log_worker.instance().send.assert_called_once_with(expected)
@pytest.mark.parametrize("with_context", [True, False])
def test_respects_explicit_task_run_id(
self,
logger: logging.Logger,
mock_log_worker: MagicMock,
flow_run: "FlowRun",
with_context: bool,
task_run: "TaskRun",
):
task_run_id = uuid.uuid4()
context = (
TaskRunContext.model_construct(task_run=task_run)
if with_context
else nullcontext()
)
with FlowRunContext.model_construct(flow_run=flow_run):
with context:
logger.warning("test-task", extra={"task_run_id": task_run_id})
expected = LogCreate.model_construct(
flow_run_id=flow_run.id,
task_run_id=task_run_id,
name=logger.name,
level=logging.WARNING,
message="test-task",
).model_dump(mode="json")
expected["timestamp"] = ANY # Tested separately
expected["__payload_size__"] = ANY # Tested separately
mock_log_worker.instance().send.assert_called_once_with(expected)
def test_does_not_emit_logs_below_level(
self, logger: logging.Logger, mock_log_worker: MagicMock
):
logger.setLevel(logging.WARNING)
logger.info("test-task", extra={"flow_run_id": uuid.uuid4()})
mock_log_worker.instance().send.assert_not_called()
def test_explicit_task_run_id_still_requires_flow_run_id(
self, logger: logging.Logger, mock_log_worker: MagicMock
):
task_run_id = uuid.uuid4()
with pytest.warns(
UserWarning, match="attempted to send logs .* without a flow run id"
):
logger.info("test-task", extra={"task_run_id": task_run_id})
mock_log_worker.instance().send.assert_not_called()
def test_sets_timestamp_from_record_created_time(
self,
logger: logging.Logger,
mock_log_worker: MagicMock,
flow_run: "FlowRun",
handler: APILogHandler,
):
# Capture the record
handler.emit = MagicMock(side_effect=handler.emit)
with FlowRunContext.model_construct(flow_run=flow_run):
logger.info("test-flow")
record = handler.emit.call_args[0][0]
log_dict = mock_log_worker.instance().send.call_args[0][0]
timestamp = log_dict["timestamp"]
if sys.version_info < (3, 11):
timestamp = _normalize_timestamp(timestamp)
assert datetime.fromisoformat(timestamp) == from_timestamp(record.created)
def test_sets_timestamp_from_time_if_missing_from_recrod(
self,
logger: logging.Logger,
mock_log_worker: MagicMock,
flow_run: "FlowRun",
handler: APILogHandler,
monkeypatch: pytest.MonkeyPatch,
):
def drop_created_and_emit(
emit: Callable[[logging.LogRecord], None], record: logging.LogRecord
):
record.created = None # type: ignore
return emit(record)
handler.emit = MagicMock(
side_effect=partial(drop_created_and_emit, handler.emit)
)
now = time.time()
monkeypatch.setattr("time.time", lambda: now)
with FlowRunContext.model_construct(flow_run=flow_run):
logger.info("test-flow")
log_dict = mock_log_worker.instance().send.call_args[0][0]
timestamp = log_dict["timestamp"]
if sys.version_info < (3, 11):
timestamp = _normalize_timestamp(timestamp)
assert datetime.fromisoformat(timestamp) == from_timestamp(now)
def test_does_not_send_logs_that_opt_out(
self,
logger: logging.Logger,
mock_log_worker: MagicMock,
task_run: "TaskRun",
):
with TaskRunContext.model_construct(task_run=task_run):
logger.info("test", extra={"send_to_api": False})
mock_log_worker.instance().send.assert_not_called()
def test_does_not_send_logs_when_handler_is_disabled(
self,
logger: logging.Logger,
mock_log_worker: MagicMock,
task_run: "TaskRun",
):
with temporary_settings(
updates={PREFECT_LOGGING_TO_API_ENABLED: "False"},
):
with TaskRunContext.model_construct(task_run=task_run):
logger.info("test")
mock_log_worker.instance().send.assert_not_called()
def test_does_not_send_logs_outside_of_run_context_with_default_setting(
self,
logger: logging.Logger,
mock_log_worker: MagicMock,
capsys: pytest.CaptureFixture[str],
):
# Warns in the main process
with pytest.warns(
UserWarning, match="attempted to send logs .* without a flow run id"
):
logger.info("test")
mock_log_worker.instance().send.assert_not_called()
# No stderr output
output = capsys.readouterr()
assert output.err == ""
def test_does_not_raise_when_logger_outside_of_run_context_with_default_setting(
self,
logger: logging.Logger,
capsys: pytest.CaptureFixture[str],
):
with pytest.warns(
UserWarning,
match=(
"Logger 'tests.test_logging' attempted to send logs to the API without"
" a flow run id."
),
):
logger.info("test")
def test_does_not_send_logs_outside_of_run_context_with_error_setting(
self,
logger: logging.Logger,
mock_log_worker: MagicMock,
capsys: pytest.CaptureFixture[str],
):
with temporary_settings(
updates={PREFECT_LOGGING_TO_API_WHEN_MISSING_FLOW: "error"},
):
with pytest.raises(
MissingContextError,
match="attempted to send logs .* without a flow run id",
):
logger.info("test")
mock_log_worker.instance().send.assert_not_called()
# No stderr output
output = capsys.readouterr()
assert output.err == ""
def test_does_not_warn_when_logger_outside_of_run_context_with_error_setting(
self,
logger: logging.Logger,
):
with temporary_settings(
updates={PREFECT_LOGGING_TO_API_WHEN_MISSING_FLOW: "error"},
):
with pytest.raises(
MissingContextError,
match=(
"Logger 'tests.test_logging' attempted to send logs to the API"
" without a flow run id."
),
):
logger.info("test")
def test_does_not_send_logs_outside_of_run_context_with_ignore_setting(
self,
logger: logging.Logger,
mock_log_worker: MagicMock,
capsys: pytest.CaptureFixture[str],
):
with temporary_settings(
updates={PREFECT_LOGGING_TO_API_WHEN_MISSING_FLOW: "ignore"},
):
logger.info("test")
mock_log_worker.instance().send.assert_not_called()
# No stderr output
output = capsys.readouterr()
assert output.err == ""
def test_does_not_raise_or_warn_when_logger_outside_of_run_context_with_ignore_setting(
self,
logger: logging.Logger,
):
with temporary_settings(
updates={PREFECT_LOGGING_TO_API_WHEN_MISSING_FLOW: "ignore"},
):
logger.info("test")
def test_does_not_send_logs_outside_of_run_context_with_warn_setting(
self,
logger: logging.Logger,
mock_log_worker: MagicMock,
capsys: pytest.CaptureFixture[str],
):
with temporary_settings(
updates={PREFECT_LOGGING_TO_API_WHEN_MISSING_FLOW: "warn"},
):
# Warns in the main process
with pytest.warns(
UserWarning, match="attempted to send logs .* without a flow run id"
):
logger.info("test")
mock_log_worker.instance().send.assert_not_called()
# No stderr output
output = capsys.readouterr()
assert output.err == ""
def test_does_not_raise_when_logger_outside_of_run_context_with_warn_setting(
self,
logger: logging.Logger,
):
with temporary_settings(
updates={PREFECT_LOGGING_TO_API_WHEN_MISSING_FLOW: "warn"},
):
with pytest.warns(
UserWarning,
match=(
"Logger 'tests.test_logging' attempted to send logs to the API"
" without a flow run id."
),
):
logger.info("test")
def test_missing_context_warning_refers_to_caller_lineno(
self,
logger: logging.Logger,
mock_log_worker: MagicMock,
):
from inspect import currentframe, getframeinfo
# Warns in the main process
with pytest.warns(
UserWarning, match="attempted to send logs .* without a flow run id"
) as warnings:
logger.info("test")
lineno = getframeinfo(currentframe()).lineno - 1 # type: ignore
# The above dynamic collects the line number so that added tests do not
# break this test
mock_log_worker.instance().send.assert_not_called()
assert warnings.pop().lineno == lineno
def test_writes_logging_errors_to_stderr(
self,
logger: logging.Logger,
mock_log_worker: MagicMock,
capsys: pytest.CaptureFixture[str],
monkeypatch: pytest.MonkeyPatch,
):
monkeypatch.setattr(
"prefect.logging.handlers.APILogHandler.prepare",
MagicMock(side_effect=RuntimeError("Oh no!")),
)
# No error raised
logger.info("test")
mock_log_worker.instance().send.assert_not_called()
# Error is in stderr
output = capsys.readouterr()
assert "RuntimeError: Oh no!" in output.err
def test_does_not_write_error_for_logs_outside_run_context_that_opt_out(
self,
logger: logging.Logger,
mock_log_worker: MagicMock,
capsys: pytest.CaptureFixture[str],
):
logger.info("test", extra={"send_to_api": False})
mock_log_worker.instance().send.assert_not_called()
output = capsys.readouterr()
assert (
"RuntimeError: Attempted to send logs to the API without a flow run id."
not in output.err
)
async def test_does_not_enqueue_logs_that_are_too_big(
self,
task_run: "TaskRun",
logger: logging.Logger,
capsys: pytest.CaptureFixture[str],
mock_log_worker: MagicMock,
):
with TaskRunContext.model_construct(task_run=task_run):
with temporary_settings(updates={PREFECT_LOGGING_TO_API_MAX_LOG_SIZE: "1"}):
logger.info("test")
mock_log_worker.instance().send.assert_called_once()
sent_log = mock_log_worker.instance().send.call_args[0][0]
output = capsys.readouterr()
assert sent_log["message"].endswith("... [truncated]")
assert "ValueError" not in output.err
def test_handler_knows_how_large_logs_are(self):
dict_log = {
"name": "prefect.flow_runs",
"level": 20,
"message": "Finished in state Completed()",
"timestamp": "2023-02-08T17:55:52.993831+00:00",
"flow_run_id": "47014fb1-9202-4a78-8739-c993d8c24415",
"task_run_id": None,
}
log_size = len(json.dumps(dict_log))
assert log_size == 211
handler = APILogHandler()
assert handler._get_payload_size(dict_log) == log_size # type: ignore[reportPrivateUsage]
@pytest.mark.usefixtures("disable_hosted_api_server")
def test_max_log_size_defaults_to_cloud_value(self):
with temporary_settings(
updates={PREFECT_API_URL: "https://api.prefect.cloud/api"},
restore_defaults={PREFECT_LOGGING_TO_API_MAX_LOG_SIZE},
) as settings:
assert settings.logging.to_api.max_log_size == 25_000
@pytest.mark.usefixtures("disable_hosted_api_server")
def test_max_log_size_defaults_to_cloud_setting(self):
with temporary_settings(
updates={
PREFECT_API_URL: "https://api.prefect.cloud/api",
PREFECT_CLOUD_MAX_LOG_SIZE: 10_000,
},
restore_defaults={PREFECT_LOGGING_TO_API_MAX_LOG_SIZE},
) as settings:
assert settings.logging.to_api.max_log_size == 10_000
@pytest.mark.usefixtures("disable_hosted_api_server")
def test_max_log_size_respects_custom_value_lower_than_cloud(self):
with temporary_settings(
updates={
PREFECT_API_URL: "https://api.prefect.cloud/api",
PREFECT_LOGGING_TO_API_MAX_LOG_SIZE: 10_000,
},
) as settings:
assert settings.logging.to_api.max_log_size == 10_000
@pytest.mark.usefixtures("disable_hosted_api_server")
def test_max_log_size_capped_at_cloud_max(self):
with temporary_settings(
updates={
PREFECT_API_URL: "https://api.prefect.cloud/api",
PREFECT_LOGGING_TO_API_MAX_LOG_SIZE: 1_000_000,
},
) as settings:
assert settings.logging.to_api.max_log_size == 25_000
@pytest.mark.usefixtures("disable_hosted_api_server")
def test_max_log_size_does_not_change_for_self_hosted(self):
with temporary_settings(
updates={PREFECT_API_URL: "http://example.com/api"},
restore_defaults={PREFECT_LOGGING_TO_API_MAX_LOG_SIZE},
) as settings:
assert settings.logging.to_api.max_log_size == 1_000_000
@pytest.mark.usefixtures("disable_hosted_api_server")
def test_max_log_size_default_when_not_connected(self):
with temporary_settings(
restore_defaults={PREFECT_API_URL, PREFECT_LOGGING_TO_API_MAX_LOG_SIZE}
) as settings: