-
Notifications
You must be signed in to change notification settings - Fork 891
Expand file tree
/
Copy pathOtlpLogExporterTests.cs
More file actions
1842 lines (1520 loc) · 67 KB
/
OtlpLogExporterTests.cs
File metadata and controls
1842 lines (1520 loc) · 67 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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation;
using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation.Serializer;
using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation.Transmission;
using OpenTelemetry.Internal;
using OpenTelemetry.Logs;
using OpenTelemetry.Proto.Trace.V1;
using OpenTelemetry.Resources;
using OpenTelemetry.Tests;
using OpenTelemetry.Trace;
using static OpenTelemetry.Proto.Common.V1.AnyValue;
using OtlpCollector = OpenTelemetry.Proto.Collector.Logs.V1;
using OtlpCommon = OpenTelemetry.Proto.Common.V1;
using OtlpLogs = OpenTelemetry.Proto.Logs.V1;
namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests;
public class OtlpLogExporterTests
{
private static readonly SdkLimitOptions DefaultSdkLimitOptions = new();
[Fact]
public void AddOtlpExporterWithNamedOptions()
{
var defaultConfigureExporterOptionsInvocations = 0;
var namedConfigureExporterOptionsInvocations = 0;
var defaultConfigureSdkLimitsOptionsInvocations = 0;
var namedConfigureSdkLimitsOptionsInvocations = 0;
using var loggerProvider = Sdk.CreateLoggerProviderBuilder()
.ConfigureServices(services =>
{
services.Configure<OtlpExporterOptions>(o => defaultConfigureExporterOptionsInvocations++);
services.Configure<LogRecordExportProcessorOptions>(o => defaultConfigureExporterOptionsInvocations++);
services.Configure<ExperimentalOptions>(o => defaultConfigureExporterOptionsInvocations++);
services.Configure<OtlpExporterOptions>("Exporter2", o => namedConfigureExporterOptionsInvocations++);
services.Configure<LogRecordExportProcessorOptions>("Exporter2", o => namedConfigureExporterOptionsInvocations++);
services.Configure<ExperimentalOptions>("Exporter2", o => namedConfigureExporterOptionsInvocations++);
services.Configure<OtlpExporterOptions>("Exporter3", o => namedConfigureExporterOptionsInvocations++);
services.Configure<LogRecordExportProcessorOptions>("Exporter3", o => namedConfigureExporterOptionsInvocations++);
services.Configure<ExperimentalOptions>("Exporter3", o => namedConfigureExporterOptionsInvocations++);
services.Configure<SdkLimitOptions>(o => defaultConfigureSdkLimitsOptionsInvocations++);
services.Configure<SdkLimitOptions>("Exporter2", o => namedConfigureSdkLimitsOptionsInvocations++);
services.Configure<SdkLimitOptions>("Exporter3", o => namedConfigureSdkLimitsOptionsInvocations++);
})
.AddOtlpExporter()
.AddOtlpExporter("Exporter2", o => { })
.AddOtlpExporter("Exporter3", o => { })
.Build();
Assert.Equal(3, defaultConfigureExporterOptionsInvocations);
Assert.Equal(6, namedConfigureExporterOptionsInvocations);
// Note: SdkLimitOptions does NOT support named options. We only allow a
// single instance for a given IServiceCollection.
Assert.Equal(1, defaultConfigureSdkLimitsOptionsInvocations);
Assert.Equal(0, namedConfigureSdkLimitsOptionsInvocations);
}
[Fact]
public void UserHttpFactoryCalledWhenUsingHttpProtobuf()
{
var options = new OtlpExporterOptions();
var defaultFactory = options.HttpClientFactory;
var invocations = 0;
options.Protocol = OtlpExportProtocol.HttpProtobuf;
options.HttpClientFactory = () =>
{
invocations++;
return defaultFactory();
};
using (var exporter = new OtlpLogExporter(options))
{
Assert.Equal(1, invocations);
}
using (var provider = Sdk.CreateLoggerProviderBuilder()
.AddOtlpExporter(o =>
{
o.Protocol = OtlpExportProtocol.HttpProtobuf;
o.HttpClientFactory = options.HttpClientFactory;
})
.Build())
{
Assert.Equal(2, invocations);
}
options.HttpClientFactory = () => null!;
Assert.Throws<InvalidOperationException>(() =>
{
using var exporter = new OtlpLogExporter(options);
});
}
[Fact]
public void ServiceProviderHttpClientFactoryNotInvoked()
{
var services = new ServiceCollection();
services.AddHttpClient();
var invocations = 0;
services.AddHttpClient("OtlpLogExporter", configureClient: (client) => invocations++);
services.AddOpenTelemetry().WithLogging(builder => builder
.AddOtlpExporter(o => o.Protocol = OtlpExportProtocol.HttpProtobuf));
using var serviceProvider = services.BuildServiceProvider();
Assert.NotNull(serviceProvider);
Assert.Equal(0, invocations);
}
[Fact(Skip = "https://github.com/open-telemetry/opentelemetry-dotnet/issues/7233")]
public void ServiceProviderHttpClientFactoryInvoked()
{
var services = new ServiceCollection();
services.AddHttpClient();
var invocations = 0;
services.AddHttpClient("OtlpLogExporter", configureClient: (client) => invocations++);
services.AddOpenTelemetry().WithLogging(builder => builder
.AddOtlpExporter(o => o.Protocol = OtlpExportProtocol.HttpProtobuf));
using var serviceProvider = services.BuildServiceProvider();
var loggerProvider = serviceProvider.GetRequiredService<LoggerProvider>();
// IHttpClientFactory integration is only enabled for OtlpLogExporter on .NET 8+.
#if NET8_0_OR_GREATER
Assert.Equal(1, invocations);
#else
Assert.Equal(0, invocations);
#endif
}
[Fact]
public void AddOtlpExporterSetsDefaultBatchExportProcessor()
{
using var loggerProvider = Sdk.CreateLoggerProviderBuilder()
.AddOtlpExporter()
.Build();
var loggerProviderSdk = loggerProvider as LoggerProviderSdk;
Assert.NotNull(loggerProviderSdk);
var batchProcessor = loggerProviderSdk.Processor as BatchLogRecordExportProcessor;
Assert.NotNull(batchProcessor);
Assert.Equal(BatchLogRecordExportProcessor.DefaultScheduledDelayMilliseconds, batchProcessor.ScheduledDelayMilliseconds);
Assert.Equal(BatchLogRecordExportProcessor.DefaultExporterTimeoutMilliseconds, batchProcessor.ExporterTimeoutMilliseconds);
Assert.Equal(BatchLogRecordExportProcessor.DefaultMaxExportBatchSize, batchProcessor.MaxExportBatchSize);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void AddOtlpLogExporterReceivesAttributesWithParseStateValueSetToFalse(bool callUseOpenTelemetry)
{
var optionsValidated = false;
var logRecords = new List<LogRecord>();
using var loggerFactory = LoggerFactory.Create(builder =>
{
ConfigureOtlpExporter(builder, callUseOpenTelemetry, logRecords: logRecords);
builder.Services.Configure<OpenTelemetryLoggerOptions>(o =>
{
optionsValidated = true;
Assert.False(o.ParseStateValues);
});
});
Assert.True(optionsValidated);
var logger = loggerFactory.CreateLogger("OtlpLogExporterTests");
logger.HelloFrom("tomato", 2.99);
Assert.Single(logRecords);
var logRecord = logRecords[0];
#pragma warning disable CS0618 // Type or member is obsolete
Assert.NotNull(logRecord.State);
#pragma warning restore CS0618 // Type or member is obsolete
Assert.NotNull(logRecord.Attributes);
}
[Theory]
[InlineData(true, false)]
[InlineData(false, false)]
[InlineData(true, true)]
[InlineData(false, true)]
public void AddOtlpLogExporterParseStateValueCanBeTurnedOff(bool parseState, bool callUseOpenTelemetry)
{
var logRecords = new List<LogRecord>();
using var loggerFactory = LoggerFactory.Create(builder =>
{
ConfigureOtlpExporter(
builder,
callUseOpenTelemetry,
configureOptions: o => o.ParseStateValues = parseState,
logRecords: logRecords);
});
#pragma warning disable CA1873
var logger = loggerFactory.CreateLogger("OtlpLogExporterTests");
logger.Log(LogLevel.Information, default, new { propertyA = "valueA" }, null, (s, e) => "Custom state log message");
#pragma warning restore CA1873
Assert.Single(logRecords);
var logRecord = logRecords[0];
#pragma warning disable CS0618 // Type or member is obsolete
if (parseState)
{
Assert.Null(logRecord.State);
Assert.NotNull(logRecord.Attributes);
// Note: We currently do not support parsing custom states which do
// not implement the standard interfaces. We return empty attributes
// for these.
Assert.Empty(logRecord.Attributes);
}
else
{
Assert.NotNull(logRecord.State);
Assert.Null(logRecord.Attributes);
}
#pragma warning restore CS0618 // Type or member is obsolete
}
[Theory]
[InlineData(true, false)]
[InlineData(false, false)]
[InlineData(true, true)]
[InlineData(false, true)]
public void AddOtlpLogExporterParseStateValueCanBeTurnedOffHosting(bool parseState, bool callUseOpenTelemetry)
{
var logRecords = new List<LogRecord>();
var hostBuilder = new HostBuilder();
hostBuilder.ConfigureLogging(logging =>
{
ConfigureOtlpExporter(logging, callUseOpenTelemetry, logRecords: logRecords);
});
hostBuilder.ConfigureServices(services =>
services.Configure<OpenTelemetryLoggerOptions>(options => options.ParseStateValues = parseState));
var host = hostBuilder.Build();
var loggerFactory = host.Services.GetService<ILoggerFactory>();
Assert.NotNull(loggerFactory);
#pragma warning disable CA1873
var logger = loggerFactory.CreateLogger("OtlpLogExporterTests");
logger.Log(LogLevel.Information, default, new { propertyA = "valueA" }, null, (s, e) => "Custom state log message");
#pragma warning restore CA1873
Assert.Single(logRecords);
var logRecord = logRecords[0];
#pragma warning disable CS0618 // Type or member is obsolete
if (parseState)
{
Assert.Null(logRecord.State);
Assert.NotNull(logRecord.Attributes);
// Note: We currently do not support parsing custom states which do
// not implement the standard interfaces. We return empty attributes
// for these.
Assert.Empty(logRecord.Attributes);
}
else
{
Assert.NotNull(logRecord.State);
Assert.Null(logRecord.Attributes);
}
#pragma warning restore CS0618 // Type or member is obsolete
}
[Fact]
public void OtlpLogRecordTestWhenStateValuesArePopulated()
{
var logRecords = new List<LogRecord>();
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.UseOpenTelemetry(
logging => logging.AddInMemoryExporter(logRecords),
options =>
{
options.IncludeFormattedMessage = true;
options.ParseStateValues = true;
});
});
var logger = loggerFactory.CreateLogger("OtlpLogExporterTests");
logger.HelloFrom("tomato", 2.99);
Assert.Single(logRecords);
var logRecord = logRecords[0];
var otlpLogRecord = ToOtlpLogs(DefaultSdkLimitOptions, new ExperimentalOptions(), logRecord);
Assert.NotNull(otlpLogRecord);
Assert.Equal("Hello from tomato 2.99.", otlpLogRecord.Body.StringValue);
Assert.Equal(3, otlpLogRecord.Attributes.Count);
var index = 0;
var attribute = otlpLogRecord.Attributes[index];
Assert.Equal("Name", attribute.Key);
Assert.Equal("tomato", attribute.Value.StringValue);
attribute = otlpLogRecord.Attributes[++index];
Assert.Equal("Price", attribute.Key);
Assert.Equal(2.99, attribute.Value.DoubleValue);
attribute = otlpLogRecord.Attributes[++index];
Assert.Equal("{OriginalFormat}", attribute.Key);
Assert.Equal("Hello from {Name} {Price}.", attribute.Value.StringValue);
}
[Theory]
[InlineData("true")]
[InlineData("false")]
[InlineData(null)]
public void CheckToOtlpLogRecordEventId(string? emitLogEventAttributes)
{
var logRecords = new List<LogRecord>();
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.UseOpenTelemetry(
logging => logging.AddInMemoryExporter(logRecords),
options =>
{
options.IncludeFormattedMessage = true;
options.ParseStateValues = true;
});
});
var logger = loggerFactory.CreateLogger("OtlpLogExporterTests");
logger.HelloFromWithEventId("tomato", 2.99);
Assert.Single(logRecords);
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?> { [ExperimentalOptions.EmitLogEventEnvVar] = emitLogEventAttributes })
.Build();
var logRecord = logRecords[0];
var otlpLogRecord = ToOtlpLogs(DefaultSdkLimitOptions, new(configuration), logRecord);
Assert.NotNull(otlpLogRecord);
Assert.Equal("Hello from tomato 2.99.", otlpLogRecord.Body.StringValue);
// Event
var otlpLogRecordAttributes = otlpLogRecord.Attributes.ToString();
if (emitLogEventAttributes == "true")
{
Assert.Contains(ExperimentalOptions.LogRecordEventIdAttribute, otlpLogRecordAttributes, StringComparison.Ordinal);
Assert.Contains("10", otlpLogRecordAttributes, StringComparison.Ordinal);
}
else
{
Assert.DoesNotContain(ExperimentalOptions.LogRecordEventIdAttribute, otlpLogRecordAttributes, StringComparison.Ordinal);
}
logRecords.Clear();
logger.HelloFromWithEventIdAndEventName("tomato", 2.99);
Assert.Single(logRecords);
logRecord = logRecords[0];
otlpLogRecord = ToOtlpLogs(DefaultSdkLimitOptions, new(configuration), logRecord);
Assert.NotNull(otlpLogRecord);
Assert.Equal("Hello from tomato 2.99.", otlpLogRecord.Body.StringValue);
Assert.Equal("MyEvent10", otlpLogRecord.EventName);
// Event
otlpLogRecordAttributes = otlpLogRecord.Attributes.ToString();
if (emitLogEventAttributes == "true")
{
Assert.Contains(ExperimentalOptions.LogRecordEventIdAttribute, otlpLogRecordAttributes, StringComparison.Ordinal);
Assert.Contains("10", otlpLogRecordAttributes, StringComparison.Ordinal);
}
else
{
Assert.DoesNotContain(ExperimentalOptions.LogRecordEventIdAttribute, otlpLogRecordAttributes, StringComparison.Ordinal);
}
}
[Fact]
public void CheckToOtlpLogRecordTimestamps()
{
var logRecords = new List<LogRecord>();
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.UseOpenTelemetry(logging => logging.AddInMemoryExporter(logRecords));
});
var logger = loggerFactory.CreateLogger("OtlpLogExporterTests");
logger.LogMessage();
var logRecord = logRecords[0];
var otlpLogRecord = ToOtlpLogs(DefaultSdkLimitOptions, new ExperimentalOptions(), logRecord);
Assert.NotNull(otlpLogRecord);
Assert.True(otlpLogRecord.TimeUnixNano > 0);
Assert.True(otlpLogRecord.ObservedTimeUnixNano > 0);
}
[Fact]
public void CheckToOtlpLogRecordTimestamps_BridgeApi_UnsetTimestamp()
{
// When the Bridge API caller leaves Timestamp as DateTime.MinValue
// (not set), the serializer must write:
// time_unix_nano = 0 (unknown/missing per OTLP spec)
// observed_time_unix_nano >= the time of observation (MUST be set per OTLP spec)
var logRecords = new List<LogRecord>();
using var loggerProvider = Sdk.CreateLoggerProviderBuilder()
.AddInMemoryExporter(logRecords)
.Build();
var bridgeLogger = loggerProvider.GetLogger("OtlpLogExporterTests");
// Capture a lower-bound for the observation timestamp before emitting.
var beforeEmitUtc = DateTime.UtcNow;
// Emit with default LogRecordData -- Timestamp stays DateTime.MinValue.
bridgeLogger.EmitLog(new LogRecordData());
Assert.Single(logRecords);
Assert.Equal(DateTime.MinValue, logRecords[0].Timestamp);
var otlpLogRecord = ToOtlpLogs(DefaultSdkLimitOptions, new ExperimentalOptions(), logRecords[0]);
Assert.NotNull(otlpLogRecord);
// time_unix_nano must be 0 -- "unknown or missing" per OTLP spec.
Assert.Equal(0UL, otlpLogRecord.TimeUnixNano);
// observed_time_unix_nano must be >= the moment we captured before emitting.
var beforeEmitNano = (ulong)new DateTimeOffset(beforeEmitUtc).ToUnixTimeNanoseconds();
Assert.True(
otlpLogRecord.ObservedTimeUnixNano >= beforeEmitNano,
$"ObservedTimeUnixNano ({otlpLogRecord.ObservedTimeUnixNano}) should be >= beforeEmitNano ({beforeEmitNano})");
}
[Fact]
public void CheckToOtlpLogRecordTraceIdSpanIdFlagWithNoActivity()
{
var logRecords = new List<LogRecord>();
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.UseOpenTelemetry(logging => logging.AddInMemoryExporter(logRecords));
});
var logger = loggerFactory.CreateLogger("OtlpLogExporterTests");
logger.LogWhenThereIsNoActivity();
var logRecord = logRecords[0];
var otlpLogRecord = ToOtlpLogs(DefaultSdkLimitOptions, new ExperimentalOptions(), logRecord);
Assert.Null(Activity.Current);
Assert.NotNull(otlpLogRecord);
Assert.True(otlpLogRecord.TraceId.IsEmpty);
Assert.True(otlpLogRecord.SpanId.IsEmpty);
Assert.Equal(0u, otlpLogRecord.Flags);
}
[Fact]
public void CheckToOtlpLogRecordSpanIdTraceIdAndFlag()
{
var logRecords = new List<LogRecord>();
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.UseOpenTelemetry(logging => logging.AddInMemoryExporter(logRecords));
});
var logger = loggerFactory.CreateLogger("OtlpLogExporterTests");
ActivityTraceId expectedTraceId = default;
ActivitySpanId expectedSpanId = default;
using (var activity = new Activity(Utils.GetCurrentMethodName()))
{
activity.Start();
logger.LogWithinAnActivity();
expectedTraceId = activity.TraceId;
expectedSpanId = activity.SpanId;
}
var logRecord = logRecords[0];
var otlpLogRecord = ToOtlpLogs(DefaultSdkLimitOptions, new ExperimentalOptions(), logRecord);
Assert.NotNull(otlpLogRecord);
Assert.Equal(expectedTraceId.ToString(), ActivityTraceId.CreateFromBytes(otlpLogRecord.TraceId.ToByteArray()).ToString());
Assert.Equal(expectedSpanId.ToString(), ActivitySpanId.CreateFromBytes(otlpLogRecord.SpanId.ToByteArray()).ToString());
Assert.Equal((uint)logRecord.TraceFlags, otlpLogRecord.Flags);
}
[Theory]
[InlineData(LogLevel.Trace)]
[InlineData(LogLevel.Debug)]
[InlineData(LogLevel.Information)]
[InlineData(LogLevel.Warning)]
[InlineData(LogLevel.Error)]
[InlineData(LogLevel.Critical)]
public void CheckToOtlpLogRecordSeverityLevelAndText(LogLevel logLevel)
{
var logRecords = new List<LogRecord>();
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.UseOpenTelemetry(
logging => logging.AddInMemoryExporter(logRecords),
options => options.IncludeFormattedMessage = true)
.AddFilter("CheckToOtlpLogRecordSeverityLevelAndText", LogLevel.Trace);
});
var logger = loggerFactory.CreateLogger("CheckToOtlpLogRecordSeverityLevelAndText");
logger.HelloFrom(logLevel, "tomato", 2.99);
Assert.Single(logRecords);
var logRecord = logRecords[0];
var otlpLogRecord = ToOtlpLogs(DefaultSdkLimitOptions, new ExperimentalOptions(), logRecord);
Assert.NotNull(otlpLogRecord);
#pragma warning disable CS0618 // Type or member is obsolete
Assert.Equal(logRecord.LogLevel.ToString(), otlpLogRecord.SeverityText);
#pragma warning restore CS0618 // Type or member is obsolete
Assert.NotNull(logRecord.Severity);
Assert.Equal((int)logRecord.Severity, (int)otlpLogRecord.SeverityNumber);
switch (logLevel)
{
case LogLevel.Trace:
Assert.Equal(OtlpLogs.SeverityNumber.Trace, otlpLogRecord.SeverityNumber);
break;
case LogLevel.Debug:
Assert.Equal(OtlpLogs.SeverityNumber.Debug, otlpLogRecord.SeverityNumber);
break;
case LogLevel.Information:
Assert.Equal(OtlpLogs.SeverityNumber.Info, otlpLogRecord.SeverityNumber);
break;
case LogLevel.Warning:
Assert.Equal(OtlpLogs.SeverityNumber.Warn, otlpLogRecord.SeverityNumber);
break;
case LogLevel.Error:
Assert.Equal(OtlpLogs.SeverityNumber.Error, otlpLogRecord.SeverityNumber);
break;
case LogLevel.Critical:
Assert.Equal(OtlpLogs.SeverityNumber.Fatal, otlpLogRecord.SeverityNumber);
break;
case LogLevel.None:
default:
break;
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void CheckToOtlpLogRecordBodyIsPopulated(bool includeFormattedMessage)
{
var logRecords = new List<LogRecord>();
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.UseOpenTelemetry(
logging => logging.AddInMemoryExporter(logRecords),
options =>
{
options.IncludeFormattedMessage = includeFormattedMessage;
options.ParseStateValues = true;
});
});
var logger = loggerFactory.CreateLogger("OtlpLogExporterTests");
// Scenario 1 - Using ExtensionMethods on ILogger.Log
logger.OpenTelemetryGreeting("Hello", "World");
Assert.Single(logRecords);
var logRecord = logRecords[0];
var otlpLogRecord = ToOtlpLogs(DefaultSdkLimitOptions, new ExperimentalOptions(), logRecord);
Assert.NotNull(otlpLogRecord);
if (includeFormattedMessage)
{
Assert.Equal(logRecord.FormattedMessage, otlpLogRecord.Body.StringValue);
}
else
{
Assert.Equal("OpenTelemetry {Greeting} {Subject}!", otlpLogRecord.Body.StringValue);
}
logRecords.Clear();
// Scenario 2 - Using the raw ILogger.Log Method
logger.Log(LogLevel.Information, default, "state", exception: null, (st, ex) => "Formatted Message");
Assert.Single(logRecords);
logRecord = logRecords[0];
otlpLogRecord = ToOtlpLogs(DefaultSdkLimitOptions, new ExperimentalOptions(), logRecord);
Assert.NotNull(otlpLogRecord);
// Formatter is always called if no template can be found.
Assert.Equal(logRecord.FormattedMessage, otlpLogRecord.Body.StringValue);
Assert.Equal(logRecord.Body, otlpLogRecord.Body.StringValue);
logRecords.Clear();
// Scenario 3 - Using the raw ILogger.Log Method, but with null
// formatter.
logger.Log(LogLevel.Information, default, "state", exception: null, formatter: null!);
Assert.Single(logRecords);
logRecord = logRecords[0];
otlpLogRecord = ToOtlpLogs(DefaultSdkLimitOptions, new ExperimentalOptions(), logRecord);
Assert.NotNull(otlpLogRecord);
// There is no formatter, we call ToString on state
Assert.Equal("state", otlpLogRecord.Body.StringValue);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void LogRecordBodyIsExportedWhenUsingBridgeApi(bool isBodySet)
{
LogRecordAttributeList attributes = default;
attributes.Add("name", "tomato");
attributes.Add("price", 2.99);
attributes.Add("{OriginalFormat}", "Hello from {name} {price}.");
var logRecords = new List<LogRecord>();
using (var loggerProvider = Sdk.CreateLoggerProviderBuilder()
.AddInMemoryExporter(logRecords)
.Build())
{
var logger = loggerProvider.GetLogger();
logger.EmitLog(new LogRecordData()
{
Body = isBodySet ? "Hello world" : null,
});
logger.EmitLog(new LogRecordData(), attributes);
}
Assert.Equal(2, logRecords.Count);
var otlpLogRecord = ToOtlpLogs(DefaultSdkLimitOptions, new ExperimentalOptions(), logRecords[0]);
Assert.NotNull(otlpLogRecord);
if (isBodySet)
{
Assert.Equal("Hello world", otlpLogRecord.Body?.StringValue);
}
else
{
Assert.Null(otlpLogRecord.Body);
}
otlpLogRecord = ToOtlpLogs(DefaultSdkLimitOptions, new ExperimentalOptions(), logRecords[1]);
Assert.NotNull(otlpLogRecord);
Assert.Equal(2, otlpLogRecord.Attributes.Count);
var index = 0;
var attribute = otlpLogRecord.Attributes[index];
Assert.Equal("name", attribute.Key);
Assert.Equal("tomato", attribute.Value.StringValue);
attribute = otlpLogRecord.Attributes[++index];
Assert.Equal("price", attribute.Key);
Assert.Equal(2.99, attribute.Value.DoubleValue);
Assert.Equal("Hello from {name} {price}.", otlpLogRecord.Body.StringValue);
}
[Fact]
public void CheckToOtlpLogRecordExceptionAttributes()
{
var logRecords = new List<LogRecord>();
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.UseOpenTelemetry(logging => logging.AddInMemoryExporter(logRecords));
});
var logger = loggerFactory.CreateLogger("OtlpLogExporterTests");
logger.ExceptionOccurred(new InvalidOperationException("Exception Message"));
var logRecord = logRecords[0];
var loggedException = logRecord.Exception;
var otlpLogRecord = ToOtlpLogs(DefaultSdkLimitOptions, new ExperimentalOptions(), logRecord);
Assert.NotNull(otlpLogRecord);
var otlpLogRecordAttributes = otlpLogRecord.Attributes.ToString();
Assert.Contains(SemanticConventions.AttributeExceptionType, otlpLogRecordAttributes, StringComparison.Ordinal);
Assert.NotNull(logRecord.Exception);
Assert.Contains(logRecord.Exception.GetType().Name, otlpLogRecordAttributes, StringComparison.Ordinal);
Assert.Contains(SemanticConventions.AttributeExceptionMessage, otlpLogRecordAttributes, StringComparison.Ordinal);
Assert.Contains(logRecord.Exception.Message, otlpLogRecordAttributes, StringComparison.Ordinal);
Assert.Contains(SemanticConventions.AttributeExceptionStacktrace, otlpLogRecordAttributes, StringComparison.Ordinal);
Assert.Contains(logRecord.Exception.ToInvariantString(), otlpLogRecordAttributes, StringComparison.Ordinal);
}
[Fact]
public void CheckToOtlpLogRecordRespectsAttributeLimits()
{
var sdkLimitOptions = new SdkLimitOptions
{
AttributeCountLimit = 2,
AttributeValueLengthLimit = 8,
};
var logRecords = new List<LogRecord>();
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.UseOpenTelemetry(
logging => logging.AddInMemoryExporter(logRecords),
options => options.ParseStateValues = true);
});
var logger = loggerFactory.CreateLogger(string.Empty);
logger.OpenTelemetryWithAttributes("I'm an attribute", "I too am an attribute", "I get dropped :(");
var logRecord = logRecords[0];
var otlpLogRecord = ToOtlpLogs(sdkLimitOptions, new(), logRecord);
Assert.NotNull(otlpLogRecord);
Assert.Equal(1u, otlpLogRecord.DroppedAttributesCount);
var attribute = TryGetAttribute(otlpLogRecord, "AttributeOne");
Assert.NotNull(attribute);
// "I'm an a" == first 8 chars from the first attribute "I'm an attribute"
Assert.Equal("I'm an a", attribute.Value.StringValue);
attribute = TryGetAttribute(otlpLogRecord, "AttributeTwo");
Assert.NotNull(attribute);
// "I too am" == first 8 chars from the second attribute "I too am an attribute"
Assert.Equal("I too am", attribute.Value.StringValue);
attribute = TryGetAttribute(otlpLogRecord, "AttributeThree");
Assert.Null(attribute);
}
[Fact]
public void Export_WhenExportClientIsProvidedInCtor_UsesProvidedExportClient()
{
// Arrange.
var testExportClient = new TestExportClient();
var exporterOptions = new OtlpExporterOptions();
using var transmissionHandler = new OtlpExporterTransmissionHandler(testExportClient, exporterOptions.TimeoutMilliseconds);
var emptyLogRecords = Array.Empty<LogRecord>();
var emptyBatch = new Batch<LogRecord>(emptyLogRecords, emptyLogRecords.Length);
using var sut = new OtlpLogExporter(
exporterOptions,
new SdkLimitOptions(),
new ExperimentalOptions(),
transmissionHandler);
// Act.
sut.Export(emptyBatch);
// Assert.
Assert.True(testExportClient.SendExportRequestCalled);
}
[Fact]
public void Export_WhenExportClientThrowsException_ReturnsExportResultFailure()
{
// Arrange.
var testExportClient = new TestExportClient(throwException: true);
var exporterOptions = new OtlpExporterOptions();
using var transmissionHandler = new OtlpExporterTransmissionHandler(testExportClient, exporterOptions.TimeoutMilliseconds);
var emptyLogRecords = Array.Empty<LogRecord>();
var emptyBatch = new Batch<LogRecord>(emptyLogRecords, emptyLogRecords.Length);
using var sut = new OtlpLogExporter(
exporterOptions,
new SdkLimitOptions(),
new ExperimentalOptions(),
transmissionHandler);
// Act.
var result = sut.Export(emptyBatch);
// Assert.
Assert.Equal(ExportResult.Failure, result);
}
[Fact]
public void Export_WhenExportIsSuccessful_ReturnsExportResultSuccess()
{
// Arrange.
var testExportClient = new TestExportClient();
var exporterOptions = new OtlpExporterOptions();
using var transmissionHandler = new OtlpExporterTransmissionHandler(testExportClient, exporterOptions.TimeoutMilliseconds);
var emptyLogRecords = Array.Empty<LogRecord>();
var emptyBatch = new Batch<LogRecord>(emptyLogRecords, emptyLogRecords.Length);
using var sut = new OtlpLogExporter(
exporterOptions,
new SdkLimitOptions(),
new ExperimentalOptions(),
transmissionHandler);
// Act.
var result = sut.Export(emptyBatch);
// Assert.
Assert.Equal(ExportResult.Success, result);
}
[Fact]
public void ToOtlpLog_WhenOptionsIncludeScopesIsFalse_DoesNotContainScopeAttribute()
{
// Arrange.
var logRecords = new List<LogRecord>(1);
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.UseOpenTelemetry(
logging => logging.AddInMemoryExporter(logRecords),
options => options.IncludeScopes = false);
});
var logger = loggerFactory.CreateLogger("Some category");
const string expectedScopeKey = "Some scope key";
const string expectedScopeValue = "Some scope value";
// Act.
using (logger.BeginScope(new List<KeyValuePair<string, object>>
{
new(expectedScopeKey, expectedScopeValue),
}))
{
logger.SomeLogInformation();
}
// Assert.
var logRecord = logRecords.Single();
var otlpLogRecord = ToOtlpLogs(DefaultSdkLimitOptions, new ExperimentalOptions(), logRecord);
Assert.NotNull(otlpLogRecord);
var actualScope = TryGetAttribute(otlpLogRecord, expectedScopeKey);
Assert.Null(actualScope);
}
[Theory]
[InlineData("Some scope value")]
[InlineData('a')]
public void ToOtlpLog_WhenOptionsIncludeScopesIsTrue_ContainsScopeAttributeStringValue(object scopeValue)
{
#if NET
Assert.NotNull(scopeValue);
#else
if (scopeValue == null)
{
throw new ArgumentNullException(nameof(scopeValue));
}
#endif
// Arrange.
var logRecords = new List<LogRecord>(1);
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.UseOpenTelemetry(
logging => logging.AddInMemoryExporter(logRecords),
options => options.IncludeScopes = true);
});
var logger = loggerFactory.CreateLogger(nameof(OtlpLogExporterTests));
const string scopeKey = "Some scope key";
// Act.
using (logger.BeginScope(new List<KeyValuePair<string, object>>
{
new(scopeKey, scopeValue),
}))
{
logger.SomeLogInformation();
}
// Assert.
var logRecord = logRecords.Single();
var otlpLogRecord = ToOtlpLogs(DefaultSdkLimitOptions, new ExperimentalOptions(), logRecord);
Assert.NotNull(otlpLogRecord);
Assert.Single(otlpLogRecord.Attributes);
var actualScope = TryGetAttribute(otlpLogRecord, scopeKey);
Assert.NotNull(actualScope);
Assert.Equal(scopeKey, actualScope.Key);
Assert.Equal(ValueOneofCase.StringValue, actualScope.Value.ValueCase);
Assert.Equal(scopeValue.ToString(), actualScope.Value.StringValue);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ToOtlpLog_WhenOptionsIncludeScopesIsTrue_ContainsScopeAttributeBoolValue(bool scopeValue)
{
// Arrange.
var logRecords = new List<LogRecord>(1);
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.UseOpenTelemetry(
logging => logging.AddInMemoryExporter(logRecords),
options => options.IncludeScopes = true);
});
var logger = loggerFactory.CreateLogger(nameof(OtlpLogExporterTests));
const string scopeKey = "Some scope key";
// Act.
using (logger.BeginScope(new List<KeyValuePair<string, object>>
{
new(scopeKey, scopeValue),
}))
{
logger.SomeLogInformation();
}
// Assert.
var logRecord = logRecords.Single();
var otlpLogRecord = ToOtlpLogs(DefaultSdkLimitOptions, new ExperimentalOptions(), logRecord);
Assert.NotNull(otlpLogRecord);
Assert.Single(otlpLogRecord.Attributes);
var actualScope = TryGetAttribute(otlpLogRecord, scopeKey);
Assert.NotNull(actualScope);
Assert.Equal(scopeKey, actualScope.Key);
Assert.Equal(ValueOneofCase.BoolValue, actualScope.Value.ValueCase);
Assert.Equal(scopeValue.ToString(), actualScope.Value.BoolValue.ToString());
}
[Theory]
[InlineData(byte.MinValue)]
[InlineData(byte.MaxValue)]
[InlineData(sbyte.MinValue)]
[InlineData(sbyte.MaxValue)]
[InlineData(short.MinValue)]
[InlineData(short.MaxValue)]
[InlineData(ushort.MinValue)]
[InlineData(ushort.MaxValue)]
[InlineData(int.MinValue)]
[InlineData(int.MaxValue)]
[InlineData(uint.MinValue)]
[InlineData(uint.MaxValue)]
[InlineData(long.MinValue)]
[InlineData(long.MaxValue)]
public void ToOtlpLog_WhenOptionsIncludeScopesIsTrue_ContainsScopeAttributeIntValue(object scopeValue)
{
#if NET
Assert.NotNull(scopeValue);
#else
if (scopeValue == null)
{
throw new ArgumentNullException(nameof(scopeValue));
}
#endif
// Arrange.
var logRecords = new List<LogRecord>(1);
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.UseOpenTelemetry(
logging => logging.AddInMemoryExporter(logRecords),
options => options.IncludeScopes = true);
});
var logger = loggerFactory.CreateLogger(nameof(OtlpLogExporterTests));
const string scopeKey = "Some scope key";