-
Notifications
You must be signed in to change notification settings - Fork 112
/
Copy pathtest_configure.py
1861 lines (1609 loc) · 75.7 KB
/
test_configure.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
from __future__ import annotations
import dataclasses
import json
import os
import sys
import threading
from contextlib import ExitStack
from pathlib import Path
from time import sleep, time
from typing import Any, Iterable, Sequence
from unittest import mock
from unittest.mock import call, patch
import inline_snapshot.extra
import pytest
import requests_mock
from inline_snapshot import snapshot
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.metrics import NoOpMeterProvider, get_meter_provider
from opentelemetry.sdk.metrics._internal.export import PeriodicExportingMetricReader
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
from opentelemetry.sdk.trace import ReadableSpan, SpanProcessor
from opentelemetry.sdk.trace.export import (
BatchSpanProcessor,
ConsoleSpanExporter,
SimpleSpanProcessor,
SpanExporter,
SpanExportResult,
)
from opentelemetry.trace import get_tracer_provider
from pydantic import __version__ as pydantic_version
from pytest import LogCaptureFixture
import logfire
from logfire import configure
from logfire._internal.config import (
GLOBAL_CONFIG,
CodeSource,
ConsoleOptions,
LogfireConfig,
LogfireCredentials,
sanitize_project_name,
)
from logfire._internal.exporters.console import ShowParentsConsoleSpanExporter
from logfire._internal.exporters.fallback import FallbackSpanExporter
from logfire._internal.exporters.file import WritingFallbackWarning
from logfire._internal.exporters.processor_wrapper import MainSpanProcessorWrapper
from logfire._internal.exporters.quiet_metrics import QuietMetricExporter
from logfire._internal.exporters.remove_pending import RemovePendingSpansExporter
from logfire._internal.exporters.wrapper import WrapperSpanExporter
from logfire._internal.integrations.executors import deserialize_config, serialize_config
from logfire._internal.tracer import PendingSpanProcessor
from logfire._internal.utils import get_version
from logfire.exceptions import LogfireConfigError
from logfire.integrations.pydantic import get_pydantic_plugin_config
from logfire.testing import TestExporter
def test_propagate_config_to_tags(exporter: TestExporter) -> None:
tags1 = logfire.with_tags('tag1', 'tag2')
tags2 = logfire.with_tags('tag3', 'tag4')
for lf in (logfire, tags1, tags2):
with lf.span('root'):
with lf.span('child'):
logfire.info('test1')
tags1.info('test2')
tags2.info('test3')
assert exporter.exported_spans_as_dict(_include_pending_spans=True) == snapshot(
[
{
'name': 'root (pending)',
'context': {'trace_id': 1, 'span_id': 2, 'is_remote': False},
'parent': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'start_time': 1000000000,
'end_time': 1000000000,
'attributes': {
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.msg_template': 'root',
'logfire.msg': 'root',
'logfire.span_type': 'pending_span',
'logfire.pending_parent_id': '0000000000000000',
},
},
{
'name': 'child (pending)',
'context': {'trace_id': 1, 'span_id': 4, 'is_remote': False},
'parent': {'trace_id': 1, 'span_id': 3, 'is_remote': False},
'start_time': 2000000000,
'end_time': 2000000000,
'attributes': {
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.msg_template': 'child',
'logfire.msg': 'child',
'logfire.span_type': 'pending_span',
'logfire.pending_parent_id': '0000000000000001',
},
},
{
'name': 'test1',
'context': {'trace_id': 1, 'span_id': 5, 'is_remote': False},
'parent': {'trace_id': 1, 'span_id': 3, 'is_remote': False},
'start_time': 3000000000,
'end_time': 3000000000,
'attributes': {
'logfire.span_type': 'log',
'logfire.level_num': 9,
'logfire.msg_template': 'test1',
'logfire.msg': 'test1',
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
},
},
{
'name': 'test2',
'context': {'trace_id': 1, 'span_id': 6, 'is_remote': False},
'parent': {'trace_id': 1, 'span_id': 3, 'is_remote': False},
'start_time': 4000000000,
'end_time': 4000000000,
'attributes': {
'logfire.span_type': 'log',
'logfire.level_num': 9,
'logfire.msg_template': 'test2',
'logfire.msg': 'test2',
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.tags': ('tag1', 'tag2'),
},
},
{
'name': 'test3',
'context': {'trace_id': 1, 'span_id': 7, 'is_remote': False},
'parent': {'trace_id': 1, 'span_id': 3, 'is_remote': False},
'start_time': 5000000000,
'end_time': 5000000000,
'attributes': {
'logfire.span_type': 'log',
'logfire.level_num': 9,
'logfire.msg_template': 'test3',
'logfire.msg': 'test3',
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.tags': ('tag3', 'tag4'),
},
},
{
'name': 'child',
'context': {'trace_id': 1, 'span_id': 3, 'is_remote': False},
'parent': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'start_time': 2000000000,
'end_time': 6000000000,
'attributes': {
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.msg_template': 'child',
'logfire.span_type': 'span',
'logfire.msg': 'child',
},
},
{
'name': 'root',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 7000000000,
'attributes': {
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.msg_template': 'root',
'logfire.span_type': 'span',
'logfire.msg': 'root',
},
},
{
'name': 'root (pending)',
'context': {'trace_id': 2, 'span_id': 9, 'is_remote': False},
'parent': {'trace_id': 2, 'span_id': 8, 'is_remote': False},
'start_time': 8000000000,
'end_time': 8000000000,
'attributes': {
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.msg_template': 'root',
'logfire.msg': 'root',
'logfire.tags': ('tag1', 'tag2'),
'logfire.span_type': 'pending_span',
'logfire.pending_parent_id': '0000000000000000',
},
},
{
'name': 'child (pending)',
'context': {'trace_id': 2, 'span_id': 11, 'is_remote': False},
'parent': {'trace_id': 2, 'span_id': 10, 'is_remote': False},
'start_time': 9000000000,
'end_time': 9000000000,
'attributes': {
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.msg_template': 'child',
'logfire.msg': 'child',
'logfire.tags': ('tag1', 'tag2'),
'logfire.span_type': 'pending_span',
'logfire.pending_parent_id': '0000000000000008',
},
},
{
'name': 'test1',
'context': {'trace_id': 2, 'span_id': 12, 'is_remote': False},
'parent': {'trace_id': 2, 'span_id': 10, 'is_remote': False},
'start_time': 10000000000,
'end_time': 10000000000,
'attributes': {
'logfire.span_type': 'log',
'logfire.level_num': 9,
'logfire.msg_template': 'test1',
'logfire.msg': 'test1',
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
},
},
{
'name': 'test2',
'context': {'trace_id': 2, 'span_id': 13, 'is_remote': False},
'parent': {'trace_id': 2, 'span_id': 10, 'is_remote': False},
'start_time': 11000000000,
'end_time': 11000000000,
'attributes': {
'logfire.span_type': 'log',
'logfire.level_num': 9,
'logfire.msg_template': 'test2',
'logfire.msg': 'test2',
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.tags': ('tag1', 'tag2'),
},
},
{
'name': 'test3',
'context': {'trace_id': 2, 'span_id': 14, 'is_remote': False},
'parent': {'trace_id': 2, 'span_id': 10, 'is_remote': False},
'start_time': 12000000000,
'end_time': 12000000000,
'attributes': {
'logfire.span_type': 'log',
'logfire.level_num': 9,
'logfire.msg_template': 'test3',
'logfire.msg': 'test3',
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.tags': ('tag3', 'tag4'),
},
},
{
'name': 'child',
'context': {'trace_id': 2, 'span_id': 10, 'is_remote': False},
'parent': {'trace_id': 2, 'span_id': 8, 'is_remote': False},
'start_time': 9000000000,
'end_time': 13000000000,
'attributes': {
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.msg_template': 'child',
'logfire.tags': ('tag1', 'tag2'),
'logfire.span_type': 'span',
'logfire.msg': 'child',
},
},
{
'name': 'root',
'context': {'trace_id': 2, 'span_id': 8, 'is_remote': False},
'parent': None,
'start_time': 8000000000,
'end_time': 14000000000,
'attributes': {
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.msg_template': 'root',
'logfire.tags': ('tag1', 'tag2'),
'logfire.span_type': 'span',
'logfire.msg': 'root',
},
},
{
'name': 'root (pending)',
'context': {'trace_id': 3, 'span_id': 16, 'is_remote': False},
'parent': {'trace_id': 3, 'span_id': 15, 'is_remote': False},
'start_time': 15000000000,
'end_time': 15000000000,
'attributes': {
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.msg_template': 'root',
'logfire.msg': 'root',
'logfire.tags': ('tag3', 'tag4'),
'logfire.span_type': 'pending_span',
'logfire.pending_parent_id': '0000000000000000',
},
},
{
'name': 'child (pending)',
'context': {'trace_id': 3, 'span_id': 18, 'is_remote': False},
'parent': {'trace_id': 3, 'span_id': 17, 'is_remote': False},
'start_time': 16000000000,
'end_time': 16000000000,
'attributes': {
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.msg_template': 'child',
'logfire.msg': 'child',
'logfire.tags': ('tag3', 'tag4'),
'logfire.span_type': 'pending_span',
'logfire.pending_parent_id': '000000000000000f',
},
},
{
'name': 'test1',
'context': {'trace_id': 3, 'span_id': 19, 'is_remote': False},
'parent': {'trace_id': 3, 'span_id': 17, 'is_remote': False},
'start_time': 17000000000,
'end_time': 17000000000,
'attributes': {
'logfire.span_type': 'log',
'logfire.level_num': 9,
'logfire.msg_template': 'test1',
'logfire.msg': 'test1',
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
},
},
{
'name': 'test2',
'context': {'trace_id': 3, 'span_id': 20, 'is_remote': False},
'parent': {'trace_id': 3, 'span_id': 17, 'is_remote': False},
'start_time': 18000000000,
'end_time': 18000000000,
'attributes': {
'logfire.span_type': 'log',
'logfire.level_num': 9,
'logfire.msg_template': 'test2',
'logfire.msg': 'test2',
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.tags': ('tag1', 'tag2'),
},
},
{
'name': 'test3',
'context': {'trace_id': 3, 'span_id': 21, 'is_remote': False},
'parent': {'trace_id': 3, 'span_id': 17, 'is_remote': False},
'start_time': 19000000000,
'end_time': 19000000000,
'attributes': {
'logfire.span_type': 'log',
'logfire.level_num': 9,
'logfire.msg_template': 'test3',
'logfire.msg': 'test3',
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.tags': ('tag3', 'tag4'),
},
},
{
'name': 'child',
'context': {'trace_id': 3, 'span_id': 17, 'is_remote': False},
'parent': {'trace_id': 3, 'span_id': 15, 'is_remote': False},
'start_time': 16000000000,
'end_time': 20000000000,
'attributes': {
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.msg_template': 'child',
'logfire.tags': ('tag3', 'tag4'),
'logfire.span_type': 'span',
'logfire.msg': 'child',
},
},
{
'name': 'root',
'context': {'trace_id': 3, 'span_id': 15, 'is_remote': False},
'parent': None,
'start_time': 15000000000,
'end_time': 21000000000,
'attributes': {
'code.filepath': 'test_configure.py',
'code.lineno': 123,
'code.function': 'test_propagate_config_to_tags',
'logfire.msg_template': 'root',
'logfire.tags': ('tag3', 'tag4'),
'logfire.span_type': 'span',
'logfire.msg': 'root',
},
},
]
)
def fresh_pydantic_plugin():
GLOBAL_CONFIG.param_manager.__dict__.pop('pydantic_plugin', None) # reset the cached_property
return get_pydantic_plugin_config()
@pytest.mark.skipif(
get_version(pydantic_version) < get_version('2.5.0'), reason='skipping for pydantic versions < v2.5'
)
def test_pydantic_plugin_include_exclude_strings():
logfire.instrument_pydantic(include='inc', exclude='exc')
assert fresh_pydantic_plugin().include == {'inc'}
assert fresh_pydantic_plugin().exclude == {'exc'}
def test_deprecated_configure_pydantic_plugin(config_kwargs: dict[str, Any]):
assert fresh_pydantic_plugin().record == 'off'
with pytest.warns(UserWarning) as warnings:
logfire.configure(**config_kwargs, pydantic_plugin=logfire.PydanticPlugin(record='all')) # type: ignore
assert fresh_pydantic_plugin().record == 'all'
assert len(warnings) == 1
assert str(warnings[0].message) == snapshot(
'The `pydantic_plugin` argument is deprecated. Use `logfire.instrument_pydantic()` instead.'
)
def test_read_config_from_environment_variables() -> None:
assert fresh_pydantic_plugin().record == 'off'
with patch.dict(os.environ, {'LOGFIRE_PYDANTIC_PLUGIN_RECORD': 'all'}):
assert fresh_pydantic_plugin().record == 'all'
with patch.dict(os.environ, {'LOGFIRE_PYDANTIC_PLUGIN_RECORD': 'test'}):
with pytest.raises(
LogfireConfigError,
match="Expected pydantic_plugin_record to be one of \\('off', 'all', 'failure', 'metrics'\\), got 'test'",
):
fresh_pydantic_plugin()
with patch.dict(os.environ, {'LOGFIRE_SEND_TO_LOGFIRE': 'not-valid'}):
with inline_snapshot.extra.raises(
snapshot(
"LogfireConfigError: Expected send_to_logfire to be an instance of one of (<class 'bool'>, typing.Literal['if-token-present']), got 'not-valid'"
)
):
configure()
assert fresh_pydantic_plugin().include == set()
with patch.dict(os.environ, {'LOGFIRE_PYDANTIC_PLUGIN_INCLUDE': 'test'}):
assert fresh_pydantic_plugin().include == {'test'}
with patch.dict(os.environ, {'LOGFIRE_PYDANTIC_PLUGIN_INCLUDE': 'test1, test2'}):
assert fresh_pydantic_plugin().include == {'test1', 'test2'}
assert fresh_pydantic_plugin().exclude == set()
with patch.dict(os.environ, {'LOGFIRE_PYDANTIC_PLUGIN_EXCLUDE': 'test'}):
assert fresh_pydantic_plugin().exclude == {'test'}
with patch.dict(os.environ, {'LOGFIRE_PYDANTIC_PLUGIN_EXCLUDE': 'test1, test2'}):
assert fresh_pydantic_plugin().exclude == {'test1', 'test2'}
def test_read_config_from_pyproject_toml(tmp_path: Path) -> None:
(tmp_path / 'pyproject.toml').write_text(
f"""
[tool.logfire]
base_url = "https://api.logfire.io"
send_to_logfire = false
project_name = "test"
console_colors = "never"
console_include_timestamp = false
data_dir = "{tmp_path}"
pydantic_plugin_record = "metrics"
pydantic_plugin_include = " test1, test2"
pydantic_plugin_exclude = "test3 ,test4"
trace_sample_rate = "0.123"
"""
)
configure(config_dir=tmp_path)
assert GLOBAL_CONFIG.advanced.base_url == 'https://api.logfire.io'
assert GLOBAL_CONFIG.send_to_logfire is False
assert GLOBAL_CONFIG.console
assert GLOBAL_CONFIG.console.colors == 'never'
assert GLOBAL_CONFIG.console.include_timestamps is False
assert GLOBAL_CONFIG.data_dir == tmp_path
assert fresh_pydantic_plugin().record == 'metrics'
assert fresh_pydantic_plugin().include == {'test1', 'test2'}
assert fresh_pydantic_plugin().exclude == {'test3', 'test4'}
assert GLOBAL_CONFIG.sampling.head == 0.123
def test_logfire_invalid_config_dir(tmp_path: Path):
(tmp_path / 'pyproject.toml').write_text('invalid-data')
with pytest.raises(
LogfireConfigError,
match='Invalid config file:',
):
LogfireConfig(config_dir=tmp_path)
def test_logfire_config_console_options() -> None:
assert LogfireConfig().console == ConsoleOptions()
assert LogfireConfig(console=False).console is False
assert LogfireConfig(console=ConsoleOptions(colors='never', verbose=True)).console == ConsoleOptions(
colors='never', verbose=True
)
with patch.dict(os.environ, {'LOGFIRE_CONSOLE': 'false'}):
assert LogfireConfig().console is False
with patch.dict(os.environ, {'LOGFIRE_CONSOLE': 'true'}):
assert LogfireConfig().console == ConsoleOptions(
colors='auto', span_style='show-parents', include_timestamps=True, verbose=False
)
with patch.dict(os.environ, {'LOGFIRE_CONSOLE_COLORS': 'never'}):
assert LogfireConfig().console == ConsoleOptions(colors='never')
with patch.dict(os.environ, {'LOGFIRE_CONSOLE_COLORS': 'test'}):
with pytest.raises(
LogfireConfigError,
match="Expected console_colors to be one of \\('auto', 'always', 'never'\\), got 'test'",
):
LogfireConfig()
with patch.dict(os.environ, {'LOGFIRE_CONSOLE_VERBOSE': '1'}):
assert LogfireConfig().console == ConsoleOptions(verbose=True)
with patch.dict(os.environ, {'LOGFIRE_CONSOLE_VERBOSE': 'false'}):
assert LogfireConfig().console == ConsoleOptions(verbose=False)
def test_configure_fallback_path(tmp_path: str) -> None:
request_mocker = requests_mock.Mocker()
request_mocker.get(
'https://logfire-api.pydantic.dev/v1/info',
json={'project_name': 'myproject', 'project_url': 'fake_project_url'},
)
class FailureExporter(SpanExporter):
def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
# This should cause FallbackSpanExporter to call its own fallback file exporter.
return SpanExportResult.FAILURE
data_dir = Path(tmp_path) / 'logfire_data'
with request_mocker:
logfire.configure(
send_to_logfire=True,
data_dir=data_dir,
token='abc1',
console=False,
)
wait_for_check_token_thread()
send_to_logfire_processor, *_ = get_span_processors()
# It's OK if these processor/exporter types change.
# We just need access to the FallbackSpanExporter either way to swap out its underlying exporter.
assert isinstance(send_to_logfire_processor, MainSpanProcessorWrapper)
batch_span_processor = send_to_logfire_processor.processor
assert isinstance(batch_span_processor, BatchSpanProcessor)
exporter = batch_span_processor.span_exporter
assert isinstance(exporter, WrapperSpanExporter)
fallback_exporter = exporter.wrapped_exporter
assert isinstance(fallback_exporter, FallbackSpanExporter)
fallback_exporter.exporter = FailureExporter()
with logfire.span('test'):
pass
assert not data_dir.exists()
path = data_dir / 'logfire_spans.bin'
with pytest.warns(WritingFallbackWarning, match=f'Failed to export spans, writing to fallback file: {path}'):
logfire.force_flush()
assert path.exists()
def test_configure_export_delay() -> None:
class TrackingExporter(SpanExporter):
def __init__(self) -> None:
self.last_export_timestamp: float | None = None
self.export_delays: list[float] = []
def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
t = time()
if self.last_export_timestamp is not None:
self.export_delays.append(t - self.last_export_timestamp)
self.last_export_timestamp = t
return SpanExportResult.SUCCESS
def configure_tracking_exporter():
request_mocker = requests_mock.Mocker()
request_mocker.get(
'https://logfire-api.pydantic.dev/v1/info',
json={'project_name': 'myproject', 'project_url': 'fake_project_url'},
)
with request_mocker:
logfire.configure(
send_to_logfire=True,
token='abc1',
console=False,
)
wait_for_check_token_thread()
send_to_logfire_processor, *_ = get_span_processors()
assert isinstance(send_to_logfire_processor, MainSpanProcessorWrapper)
batch_span_processor = send_to_logfire_processor.processor
assert isinstance(batch_span_processor, BatchSpanProcessor)
batch_span_processor.span_exporter = TrackingExporter()
return batch_span_processor.span_exporter
def check_delays(exp: TrackingExporter, min_delay: float, max_delay: float) -> None:
for delay in exp.export_delays:
assert min_delay < delay < max_delay, f'delay was {delay}, which is not between {min_delay} and {max_delay}'
# test the default value
exporter = configure_tracking_exporter()
while not exporter.export_delays:
with logfire.span('test'):
pass
sleep(0.1)
check_delays(exporter, 0.4, 1.0) # our default is 500ms
# test a very small value
with patch.dict(os.environ, {'OTEL_BSP_SCHEDULE_DELAY': '1'}):
exporter = configure_tracking_exporter()
while not exporter.export_delays:
with logfire.span('test'):
pass
sleep(0.03)
check_delays(exporter, 0.0, 0.1) # since we set 1ms it should be a very short delay
def test_configure_service_version(tmp_path: str) -> None:
request_mocker = requests_mock.Mocker()
request_mocker.get(
'https://logfire-api.pydantic.dev/v1/info',
json={'project_name': 'myproject', 'project_url': 'fake_project_url'},
)
import subprocess
git_sha = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('ascii').strip()
with request_mocker:
configure(token='abc2', service_version='1.2.3')
assert GLOBAL_CONFIG.service_version == '1.2.3'
configure(token='abc3')
assert GLOBAL_CONFIG.service_version == git_sha
dir = os.getcwd()
try:
os.chdir(tmp_path)
configure(token='abc4')
assert GLOBAL_CONFIG.service_version is None
finally:
os.chdir(dir)
wait_for_check_token_thread()
def test_otel_service_name_env_var(config_kwargs: dict[str, Any], exporter: TestExporter) -> None:
with patch.dict(os.environ, {'OTEL_SERVICE_NAME': 'potato'}):
configure(service_version='1.2.3', **config_kwargs)
logfire.info('test1')
assert exporter.exported_spans_as_dict(include_resources=True) == snapshot(
[
{
'name': 'test1',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 1000000000,
'attributes': {
'logfire.span_type': 'log',
'logfire.level_num': 9,
'logfire.msg_template': 'test1',
'logfire.msg': 'test1',
'code.filepath': 'test_configure.py',
'code.function': 'test_otel_service_name_env_var',
'code.lineno': 123,
},
'resource': {
'attributes': {
'telemetry.sdk.language': 'python',
'telemetry.sdk.name': 'opentelemetry',
'telemetry.sdk.version': '0.0.0',
'service.name': 'potato',
'service.version': '1.2.3',
'service.instance.id': '00000000000000000000000000000000',
'process.pid': 1234,
}
},
}
]
)
def test_otel_otel_resource_attributes_env_var(config_kwargs: dict[str, Any], exporter: TestExporter) -> None:
with patch.dict(
os.environ,
{'OTEL_RESOURCE_ATTRIBUTES': 'service.name=banana,service.version=1.2.3,service.instance.id=instance_id'},
):
configure(**config_kwargs)
logfire.info('test1')
assert exporter.exported_spans_as_dict(include_resources=True) == snapshot(
[
{
'name': 'test1',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 1000000000,
'attributes': {
'logfire.span_type': 'log',
'logfire.level_num': 9,
'logfire.msg_template': 'test1',
'logfire.msg': 'test1',
'code.filepath': 'test_configure.py',
'code.function': 'test_otel_otel_resource_attributes_env_var',
'code.lineno': 123,
},
'resource': {
'attributes': {
'telemetry.sdk.language': 'python',
'telemetry.sdk.name': 'opentelemetry',
'telemetry.sdk.version': '0.0.0',
'service.name': 'banana',
'service.version': '1.2.3',
'service.instance.id': 'instance_id',
'process.pid': 1234,
}
},
}
]
)
def test_otel_service_name_has_priority_on_otel_resource_attributes_service_name_env_var(
config_kwargs: dict[str, Any], exporter: TestExporter
) -> None:
with patch.dict(
os.environ,
dict(OTEL_SERVICE_NAME='potato', OTEL_RESOURCE_ATTRIBUTES='service.name=banana,service.version=1.2.3'),
):
configure(**config_kwargs)
logfire.info('test1')
assert exporter.exported_spans_as_dict(include_resources=True) == snapshot(
[
{
'name': 'test1',
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
'parent': None,
'start_time': 1000000000,
'end_time': 1000000000,
'attributes': {
'logfire.span_type': 'log',
'logfire.level_num': 9,
'logfire.msg_template': 'test1',
'logfire.msg': 'test1',
'code.filepath': 'test_configure.py',
'code.function': 'test_otel_service_name_has_priority_on_otel_resource_attributes_service_name_env_var',
'code.lineno': 123,
},
'resource': {
'attributes': {
'telemetry.sdk.language': 'python',
'telemetry.sdk.name': 'opentelemetry',
'telemetry.sdk.version': '0.0.0',
'service.name': 'banana',
'service.version': '1.2.3',
'service.instance.id': '00000000000000000000000000000000',
'process.pid': 1234,
}
},
}
]
)
def test_config_serializable():
"""
Tests that by default, the logfire config can be serialized in the way that we do when sending it to another process.
Here's an example of a configuration that (as of writing) fails to serialize:
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
import logfire
from logfire._internal.exporters.console import SimpleConsoleSpanExporter
from logfire._internal.integrations.executors import serialize_config
logfire.configure(additional_span_processors=[SimpleSpanProcessor(SimpleConsoleSpanExporter())])
serialize_config() # fails because SimpleConsoleSpanExporter contains sys.stdout
This implies that the default processors cannot be stored in the config alongside user-defined processors.
In particular we also need to check that config values that are dataclasses are handled properly:
they get serialized to dicts (which dataclasses.asdict does automatically),
and deserialized back to dataclasses (which we have to do manually).
"""
logfire.configure(
send_to_logfire=False,
console=logfire.ConsoleOptions(verbose=True),
sampling=logfire.SamplingOptions(),
scrubbing=logfire.ScrubbingOptions(),
code_source=logfire.CodeSource(repository='https://github.com/pydantic/logfire', revision='main'),
)
for field in dataclasses.fields(GLOBAL_CONFIG):
# Check that the full set of dataclass fields is known.
# If a new field appears here, make sure it gets deserialized properly in configure, and tested here.
assert dataclasses.is_dataclass(getattr(GLOBAL_CONFIG, field.name)) == (
field.name in ['console', 'sampling', 'scrubbing', 'advanced', 'code_source']
)
serialized = serialize_config()
deserialize_config(serialized)
serialized2 = serialize_config()
def normalize(s: dict[str, Any]) -> dict[str, Any]:
for value in s.values():
assert not dataclasses.is_dataclass(value)
# This gets deepcopied by dataclasses.asdict, so we can't compare them directly
del s['advanced']['id_generator']
return s
assert normalize(serialized) == normalize(serialized2)
assert isinstance(GLOBAL_CONFIG.console, logfire.ConsoleOptions)
assert isinstance(GLOBAL_CONFIG.sampling, logfire.SamplingOptions)
assert isinstance(GLOBAL_CONFIG.scrubbing, logfire.ScrubbingOptions)
assert isinstance(GLOBAL_CONFIG.advanced, logfire.AdvancedOptions)
def test_config_serializable_console_false():
logfire.configure(send_to_logfire=False, console=False)
assert GLOBAL_CONFIG.console is False
deserialize_config(serialize_config())
assert GLOBAL_CONFIG.console is False
def test_sanitize_project_name():
assert sanitize_project_name('foo') == 'foo'
assert sanitize_project_name('FOO') == 'foo'
assert sanitize_project_name(' foo - bar!!') == 'foobar'
assert sanitize_project_name(' Foo - BAR!!') == 'foobar'
assert sanitize_project_name('') == 'untitled'
assert sanitize_project_name('-') == 'untitled'
assert sanitize_project_name('...') == 'untitled'
long_name = 'abcdefg' * 20
assert sanitize_project_name(long_name) == long_name[:41]
def test_initialize_project_use_existing_project_no_projects(tmp_dir_cwd: Path, tmp_path: Path):
auth_file = tmp_path / 'default.toml'
auth_file.write_text(
'[tokens."https://logfire-api.pydantic.dev"]\ntoken = "fake_user_token"\nexpiration = "2099-12-31T23:59:59"'
)
with ExitStack() as stack:
stack.enter_context(mock.patch('logfire._internal.config.DEFAULT_FILE', auth_file))
confirm_mock = stack.enter_context(mock.patch('rich.prompt.Confirm.ask', side_effect=[True, True]))
stack.enter_context(mock.patch('rich.prompt.Prompt.ask', side_effect=['', 'myproject', '']))
request_mocker = requests_mock.Mocker()
stack.enter_context(request_mocker)
request_mocker.get('https://logfire-api.pydantic.dev/v1/projects/', json=[])
request_mocker.get(
'https://logfire-api.pydantic.dev/v1/organizations/', json=[{'organization_name': 'fake_org'}]
)
request_mocker.get(
'https://logfire-api.pydantic.dev/v1/info',
json={'project_name': 'myproject', 'project_url': 'fake_project_url'},
)
create_project_response = {
'json': {
'project_name': 'myproject',
'token': 'fake_token',
'project_url': 'fake_project_url',
}
}
request_mocker.post('https://logfire-api.pydantic.dev/v1/projects/fake_org', [create_project_response])
logfire.configure(send_to_logfire=True)
wait_for_check_token_thread()
assert confirm_mock.mock_calls == [
call('The project will be created in the organization "fake_org". Continue?', default=True),
]
def test_initialize_project_use_existing_project(tmp_dir_cwd: Path, tmp_path: Path, capsys: pytest.CaptureFixture[str]):
auth_file = tmp_path / 'default.toml'
auth_file.write_text(
'[tokens."https://logfire-api.pydantic.dev"]\ntoken = "fake_user_token"\nexpiration = "2099-12-31T23:59:59"'
)
with ExitStack() as stack:
stack.enter_context(mock.patch('logfire._internal.config.DEFAULT_FILE', auth_file))
confirm_mock = stack.enter_context(mock.patch('rich.prompt.Confirm.ask', side_effect=[True, True]))
prompt_mock = stack.enter_context(mock.patch('rich.prompt.Prompt.ask', side_effect=['1', '']))
request_mocker = requests_mock.Mocker()
stack.enter_context(request_mocker)
request_mocker.get(
'https://logfire-api.pydantic.dev/v1/projects/',
json=[{'organization_name': 'fake_org', 'project_name': 'fake_project'}],
)
request_mocker.get(
'https://logfire-api.pydantic.dev/v1/info',
json={'project_name': 'myproject', 'project_url': 'fake_project_url'},
)
create_project_response = {
'json': {
'project_name': 'myproject',
'token': 'fake_token',
'project_url': 'fake_project_url',
}
}
request_mocker.post(
'https://logfire-api.pydantic.dev/v1/organizations/fake_org/projects/fake_project/write-tokens/',
[create_project_response],
)
logfire.configure(send_to_logfire=True)
assert confirm_mock.mock_calls == [
call('Do you want to use one of your existing projects? ', default=True),
]
assert prompt_mock.mock_calls == [
call(
'Please select one of the following projects by number:\n1. fake_org/fake_project\n',
choices=['1'],
default='1',
),
call(
'Project initialized successfully. You will be able to view it at: fake_project_url\nPress Enter to continue',
),
]
wait_for_check_token_thread()
assert capsys.readouterr().err == 'Logfire project URL: fake_project_url\n'
assert json.loads((tmp_dir_cwd / '.logfire/logfire_credentials.json').read_text()) == {
**create_project_response['json'],
'logfire_api_url': 'https://logfire-api.pydantic.dev',
}
def test_initialize_project_not_using_existing_project(
tmp_dir_cwd: Path, tmp_path: Path, capsys: pytest.CaptureFixture[str]
):
auth_file = tmp_path / 'default.toml'
auth_file.write_text(
'[tokens."https://logfire-api.pydantic.dev"]\ntoken = "fake_user_token"\nexpiration = "2099-12-31T23:59:59"'
)
with ExitStack() as stack:
stack.enter_context(mock.patch('logfire._internal.config.DEFAULT_FILE', auth_file))
confirm_mock = stack.enter_context(mock.patch('rich.prompt.Confirm.ask', side_effect=[False, True]))
prompt_mock = stack.enter_context(mock.patch('rich.prompt.Prompt.ask', side_effect=['my-project', '']))
request_mocker = requests_mock.Mocker()
stack.enter_context(request_mocker)
request_mocker.get(
'https://logfire-api.pydantic.dev/v1/organizations/', json=[{'organization_name': 'fake_org'}]
)
request_mocker.get(
'https://logfire-api.pydantic.dev/v1/info',