forked from PrefectHQ/prefect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_logging.py
1538 lines (1220 loc) · 48.7 KB
/
test_logging.py
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
import json
import logging
import sys
import time
import uuid
from contextlib import nullcontext
from functools import partial
from io import StringIO
from unittest.mock import ANY, MagicMock
import pendulum
import pytest
from rich.color import Color, ColorType
from rich.console import Console
from rich.highlighter import NullHighlighter, ReprHighlighter
from rich.style import Style
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.context import FlowRunContext, TaskRunContext
from prefect.exceptions import MissingContextError
from prefect.logging import LogEavesdropper
from prefect.logging.configuration import (
DEFAULT_LOGGING_SETTINGS_PATH,
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
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,
patch_print,
task_run_logger,
)
from prefect.server.schemas.actions import LogCreate
from prefect.settings import (
PREFECT_API_KEY,
PREFECT_LOGGING_COLORS,
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_TEST_MODE,
temporary_settings,
)
from prefect.testing.cli import temporary_console_width
from prefect.testing.utilities import AsyncMock
from prefect.utilities.names import obfuscate
@pytest.fixture
def dictConfigMock(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 = None
yield mock
prefect.logging.configuration.PROCESS_LOGGING_CONFIG = old
@pytest.fixture
async def logger_test_deployment(prefect_client):
"""
A deployment with a flow that returns information about the given loggers
"""
@prefect.flow
def my_flow(loggers=["foo", "bar", "prefect"]):
import logging
settings = {}
for logger_name in loggers:
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, dictConfigMock):
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):
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, dictConfigMock):
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, dictConfigMock, 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 = {}
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 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)
@pytest.mark.parametrize("name", ["default", None, ""])
def test_get_logger_returns_prefect_logger_by_default(name):
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):
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 mock_log_worker(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):
yield APILogHandler()
@pytest.fixture
def logger(self, handler):
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):
handler = APILogHandler()
handler.close()
mock_log_worker.drain_all.assert_not_called()
async def test_logs_can_still_be_sent_after_close(
self, logger, handler, flow_run, prefect_client
):
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()
logs = await prefect_client.read_logs()
assert len(logs) == 2
async def test_logs_can_still_be_sent_after_flush(
self, logger, handler, flow_run, prefect_client
):
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()
logs = await prefect_client.read_logs()
assert len(logs) == 2
async def test_sync_flush_from_async_context(
self, logger, handler, flow_run, prefect_client
):
logger.info("Test", extra={"flow_run_id": flow_run.id})
handler.flush()
# Yield to the worker thread
time.sleep(2)
logs = await prefect_client.read_logs()
assert len(logs) == 1
def test_sync_flush_from_global_event_loop(self, logger, handler, flow_run):
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, handler, flow_run):
logger.info("Test", extra={"flow_run_id": flow_run.id})
handler.flush()
def test_sends_task_run_log_to_worker(self, logger, mock_log_worker, task_run):
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, mock_log_worker, flow_run):
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)
@pytest.mark.parametrize("with_context", [True, False])
def test_respects_explicit_flow_run_id(
self, logger, mock_log_worker, flow_run, with_context
):
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, mock_log_worker, flow_run, with_context, task_run
):
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, mock_log_worker):
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, mock_log_worker
):
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, mock_log_worker, flow_run, handler
):
# 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]
assert (
log_dict["timestamp"]
== pendulum.from_timestamp(record.created).to_iso8601_string()
)
def test_sets_timestamp_from_time_if_missing_from_recrod(
self, logger, mock_log_worker, flow_run, handler, monkeypatch
):
def drop_created_and_emit(emit, record):
record.created = None
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]
assert log_dict["timestamp"] == pendulum.from_timestamp(now).to_iso8601_string()
def test_does_not_send_logs_that_opt_out(self, logger, mock_log_worker, task_run):
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, mock_log_worker, task_run
):
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, mock_log_worker, capsys
):
# 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,
):
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, mock_log_worker, capsys
):
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,
):
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, mock_log_worker, capsys
):
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,
):
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, mock_log_worker, capsys
):
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
):
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, mock_log_worker
):
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
# 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, mock_log_worker, capsys, 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, mock_log_worker, capsys
):
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, logger, capsys, mock_log_worker
):
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_not_called()
output = capsys.readouterr()
assert "ValueError" in output.err
assert "is greater than the max size of 1" 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
class TestAPILogWorker:
@pytest.fixture
async def worker(self):
return APILogWorker.instance()
@pytest.fixture
def log_dict(self):
return LogCreate(
flow_run_id=uuid.uuid4(),
task_run_id=uuid.uuid4(),
name="test.logger",
level=10,
timestamp=pendulum.now("utc"),
message="hello",
).model_dump(mode="json")
async def test_send_logs_single_record(self, log_dict, prefect_client, worker):
worker.send(log_dict)
await worker.drain()
logs = await prefect_client.read_logs()
assert len(logs) == 1
assert logs[0].model_dump(include=log_dict.keys(), mode="json") == log_dict
async def test_send_logs_many_records(self, log_dict, prefect_client, worker):
# Use the read limit as the count since we'd need multiple read calls otherwise
count = prefect.settings.PREFECT_API_DEFAULT_LIMIT.value()
log_dict.pop("message")
for i in range(count):
new_log = log_dict.copy()
new_log["message"] = str(i)
worker.send(new_log)
await worker.drain()
logs = await prefect_client.read_logs()
assert len(logs) == count
for log in logs:
assert (
log.model_dump(
include=log_dict.keys(), exclude={"message"}, mode="json"
)
== log_dict
)
assert len(set(log.message for log in logs)) == count, "Each log is unique"
async def test_send_logs_writes_exceptions_to_stderr(
self, log_dict, capsys, monkeypatch, worker
):
monkeypatch.setattr(
"prefect.client.orchestration.PrefectClient.create_logs",
MagicMock(side_effect=ValueError("Test")),
)
worker.send(log_dict)
await worker.drain()
err = capsys.readouterr().err
assert "--- Error logging to API ---" in err
assert "ValueError: Test" in err
async def test_send_logs_batches_by_size(self, log_dict, monkeypatch):
mock_create_logs = AsyncMock()
monkeypatch.setattr(
"prefect.client.orchestration.PrefectClient.create_logs", mock_create_logs
)
log_size = APILogHandler()._get_payload_size(log_dict)
with temporary_settings(
updates={
PREFECT_LOGGING_TO_API_BATCH_SIZE: log_size + 1,
PREFECT_LOGGING_TO_API_MAX_LOG_SIZE: log_size,
}
):
worker = APILogWorker.instance()
worker.send(log_dict)
worker.send(log_dict)
worker.send(log_dict)
await worker.drain()
assert mock_create_logs.call_count == 3
async def test_logs_are_sent_immediately_when_stopped(
self, log_dict, prefect_client
):
# Set a long interval
start_time = time.time()
with temporary_settings(updates={PREFECT_LOGGING_TO_API_BATCH_INTERVAL: "10"}):
worker = APILogWorker.instance()
worker.send(log_dict)
worker.send(log_dict)
await worker.drain()
end_time = time.time()
assert (
end_time - start_time
) < 5 # An arbitrary time less than the 10s interval
logs = await prefect_client.read_logs()
assert len(logs) == 2
async def test_logs_are_sent_immediately_when_flushed(
self, log_dict, prefect_client, worker
):
# Set a long interval
start_time = time.time()
with temporary_settings(updates={PREFECT_LOGGING_TO_API_BATCH_INTERVAL: "10"}):
worker.send(log_dict)
worker.send(log_dict)
await worker.drain()
end_time = time.time()
assert (
end_time - start_time
) < 5 # An arbitrary time less than the 10s interval
logs = await prefect_client.read_logs()
assert len(logs) == 2
def test_flow_run_logger(flow_run):
logger = flow_run_logger(flow_run)
assert logger.name == "prefect.flow_runs"
assert logger.extra == {
"flow_run_name": flow_run.name,
"flow_run_id": str(flow_run.id),
"flow_name": "<unknown>",
}
def test_flow_run_logger_with_flow(flow_run):
@flow(name="foo")
def test_flow():
pass
logger = flow_run_logger(flow_run, test_flow)
assert logger.extra["flow_name"] == "foo"
def test_flow_run_logger_with_kwargs(flow_run):
logger = flow_run_logger(flow_run, foo="test", flow_run_name="bar")
assert logger.extra["foo"] == "test"
assert logger.extra["flow_run_name"] == "bar"
def test_task_run_logger(task_run):
logger = task_run_logger(task_run)
assert logger.name == "prefect.task_runs"
assert logger.extra == {
"task_run_name": task_run.name,
"task_run_id": str(task_run.id),
"flow_run_id": str(task_run.flow_run_id),
"flow_run_name": "<unknown>",
"flow_name": "<unknown>",
"task_name": "<unknown>",
}
def test_task_run_logger_with_task(task_run):
@task(name="task_run_logger_with_task")
def test_task():
pass
logger = task_run_logger(task_run, test_task)
assert logger.extra["task_name"] == "task_run_logger_with_task"
def test_task_run_logger_with_flow_run(task_run, flow_run):
logger = task_run_logger(task_run, flow_run=flow_run)
assert logger.extra["flow_run_id"] == str(task_run.flow_run_id)
assert logger.extra["flow_run_name"] == flow_run.name
def test_task_run_logger_with_flow(task_run):
@flow(name="foo")
def test_flow():
pass
logger = task_run_logger(task_run, flow=test_flow)
assert logger.extra["flow_name"] == "foo"
def test_task_run_logger_with_flow_run_from_context(task_run, flow_run):
@flow(name="foo")
def test_flow():
pass
with FlowRunContext.model_construct(flow_run=flow_run, flow=test_flow):
logger = task_run_logger(task_run)
assert (
logger.extra["flow_run_id"] == str(task_run.flow_run_id) == str(flow_run.id)
)
assert logger.extra["flow_run_name"] == flow_run.name
assert logger.extra["flow_name"] == test_flow.name == "foo"
def test_run_logger_with_flow_run_context_without_parent_flow_run_id(caplog):
"""Test that get_run_logger works when called from a constructed FlowRunContext"""
with FlowRunContext.model_construct(flow_run=None, flow=None):
logger = get_run_logger()
with caplog.at_level(logging.INFO):
logger.info("test3141592")
assert "prefect.flow_runs" in caplog.text
assert "test3141592" in caplog.text
assert logger.extra["flow_run_id"] == "<unknown>"
assert logger.extra["flow_run_name"] == "<unknown>"
assert logger.extra["flow_name"] == "<unknown>"
async def test_run_logger_with_task_run_context_without_parent_flow_run_id(
prefect_client, caplog
):
"""Test that get_run_logger works when passed a constructed TaskRunContext"""
@task
def foo():
pass
task_run = await prefect_client.create_task_run(
foo, flow_run_id=None, dynamic_key=""
)
task_run_context = TaskRunContext.model_construct(
task=foo, task_run=task_run, client=prefect_client
)
logger = get_run_logger(task_run_context)
with caplog.at_level(logging.INFO):
logger.info("test3141592")
assert "prefect.task_runs" in caplog.text
assert "test3141592" in caplog.text
def test_task_run_logger_with_kwargs(task_run):
logger = task_run_logger(task_run, foo="test", task_run_name="bar")
assert logger.extra["foo"] == "test"
assert logger.extra["task_run_name"] == "bar"
def test_run_logger_fails_outside_context():
with pytest.raises(MissingContextError, match="no active flow or task run context"):
get_run_logger()
async def test_run_logger_with_explicit_context_of_invalid_type():
with pytest.raises(TypeError, match="Received unexpected type 'str' for context."):
get_run_logger("my man!")
async def test_run_logger_with_explicit_context(
prefect_client, flow_run, local_filesystem
):
@task
def foo():
pass
task_run = await prefect_client.create_task_run(foo, flow_run.id, dynamic_key="")
context = TaskRunContext.model_construct(
task=foo,
task_run=task_run,
client=prefect_client,
)
logger = get_run_logger(context)
assert logger.name == "prefect.task_runs"
assert logger.extra == {
"task_name": foo.name,
"task_run_id": str(task_run.id),
"task_run_name": task_run.name,
"flow_run_id": str(flow_run.id),
"flow_name": "<unknown>",
"flow_run_name": "<unknown>",
}
async def test_run_logger_with_explicit_context_overrides_existing(
prefect_client, flow_run, local_filesystem
):
@task
def foo():
pass
@task
def bar():
pass
task_run = await prefect_client.create_task_run(foo, flow_run.id, dynamic_key="")
# Use `bar` instead of `foo` in context
context = TaskRunContext.model_construct(
task=bar,
task_run=task_run,
client=prefect_client,
)
logger = get_run_logger(context)
assert logger.extra["task_name"] == bar.name
async def test_run_logger_in_flow(prefect_client):
@flow
def test_flow():
return get_run_logger()
state = test_flow(return_state=True)
flow_run = await prefect_client.read_flow_run(state.state_details.flow_run_id)
logger = await state.result()
assert logger.name == "prefect.flow_runs"
assert logger.extra == {
"flow_name": test_flow.name,
"flow_run_id": str(flow_run.id),
"flow_run_name": flow_run.name,
}
async def test_run_logger_extra_data(prefect_client):
@flow
def test_flow():
return get_run_logger(foo="test", flow_name="bar")
state = test_flow(return_state=True)
flow_run = await prefect_client.read_flow_run(state.state_details.flow_run_id)
logger = await state.result()
assert logger.name == "prefect.flow_runs"
assert logger.extra == {
"flow_name": "bar",
"foo": "test",
"flow_run_id": str(flow_run.id),
"flow_run_name": flow_run.name,
}
async def test_run_logger_in_nested_flow(prefect_client):
@flow
def child_flow():
return get_run_logger()
@flow
def test_flow():
return child_flow(return_state=True)
child_state = await test_flow(return_state=True).result()
flow_run = await prefect_client.read_flow_run(child_state.state_details.flow_run_id)
logger = await child_state.result()
assert logger.name == "prefect.flow_runs"
assert logger.extra == {
"flow_name": child_flow.name,
"flow_run_id": str(flow_run.id),
"flow_run_name": flow_run.name,
}
async def test_run_logger_in_task(prefect_client, events_pipeline):
@task
def test_task():
return get_run_logger()
@flow
def test_flow():
return test_task(return_state=True)
flow_state = test_flow(return_state=True)
flow_run = await prefect_client.read_flow_run(flow_state.state_details.flow_run_id)
task_state = await flow_state.result()