|
| 1 | +// Licensed to Elasticsearch B.V under one or more agreements. |
| 2 | +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. |
| 3 | +// See the LICENSE file in the project root for more information |
| 4 | + |
| 5 | +using OpenTelemetry; |
| 6 | +using OpenTelemetry.Logs; |
| 7 | +using Xunit.Abstractions; |
| 8 | + |
| 9 | +namespace Elastic.OpenTelemetry.Tests.Logging; |
| 10 | + |
| 11 | +public class ElasticLoggingDefaults(ITestOutputHelper output) |
| 12 | +{ |
| 13 | + private readonly ITestOutputHelper _output = output; |
| 14 | + |
| 15 | + [Fact] |
| 16 | + public async Task FormattedMessageAndScopesOptions_AreEnabled() |
| 17 | + { |
| 18 | + var exportedItems = new List<LogRecord>(); |
| 19 | + |
| 20 | + var host = Host.CreateDefaultBuilder(); |
| 21 | + host.ConfigureServices(s => |
| 22 | + { |
| 23 | + var options = new ElasticOpenTelemetryOptions() |
| 24 | + { |
| 25 | + SkipOtlpExporter = true, |
| 26 | + AdditionalLogger = new TestLogger(_output) |
| 27 | + }; |
| 28 | + |
| 29 | + s.AddElasticOpenTelemetry(options) |
| 30 | + .WithLogging(lpb => lpb.AddInMemoryExporter(exportedItems)); |
| 31 | + }); |
| 32 | + |
| 33 | + var ctx = new CancellationTokenRegistration(); |
| 34 | + |
| 35 | + using (var app = host.Build()) |
| 36 | + { |
| 37 | + _ = app.RunAsync(ctx.Token); |
| 38 | + |
| 39 | + var factory = app.Services.GetRequiredService<ILoggerFactory>(); |
| 40 | + var logger = factory.CreateLogger("Test"); |
| 41 | + |
| 42 | + using (logger.BeginScope(new List<KeyValuePair<string, object>> |
| 43 | + { |
| 44 | + new("customData", "aCustomValue"), |
| 45 | + })) |
| 46 | + { |
| 47 | + logger.LogWarning("This is a {WhatAmI}", "warning"); |
| 48 | + } |
| 49 | + |
| 50 | + await ctx.DisposeAsync(); |
| 51 | + } |
| 52 | + |
| 53 | + var logRecord = exportedItems.Last(); |
| 54 | + |
| 55 | + Assert.Equal("This is a warning", logRecord.FormattedMessage); |
| 56 | + |
| 57 | + logRecord.ForEachScope<object?>((scope, _) => |
| 58 | + { |
| 59 | + var values = scope.Scope as IEnumerable<KeyValuePair<string, object>>; |
| 60 | + |
| 61 | + Assert.NotNull(values); |
| 62 | + var entry = Assert.Single(values); |
| 63 | + |
| 64 | + Assert.Equal("customData", entry.Key); |
| 65 | + Assert.Equal("aCustomValue", entry.Value); |
| 66 | + }, null); |
| 67 | + } |
| 68 | +} |
0 commit comments