-
-
Notifications
You must be signed in to change notification settings - Fork 230
Expand file tree
/
Copy pathSentryStructuredLoggerTests.cs
More file actions
314 lines (255 loc) · 11.3 KB
/
SentryStructuredLoggerTests.cs
File metadata and controls
314 lines (255 loc) · 11.3 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
#nullable enable
namespace Sentry.Tests;
/// <summary>
/// <see href="https://develop.sentry.dev/sdk/telemetry/logs/"/>
/// </summary>
public partial class SentryStructuredLoggerTests : IDisposable
{
internal sealed class Fixture
{
public Fixture()
{
DiagnosticLogger = new InMemoryDiagnosticLogger();
Hub = Substitute.For<IHub>();
Options = new SentryOptions
{
Debug = true,
DiagnosticLogger = DiagnosticLogger,
};
Clock = new MockClock(new DateTimeOffset(2025, 04, 22, 14, 51, 00, 789, TimeSpan.FromHours(2)));
BatchSize = 2;
BatchTimeout = Timeout.InfiniteTimeSpan;
TraceId = SentryId.Create();
SpanId = Sentry.SpanId.Create();
Hub.IsEnabled.Returns(true);
var span = Substitute.For<ISpan>();
span.TraceId.Returns(TraceId);
span.SpanId.Returns(SpanId.Value);
Hub.GetSpan().Returns(span);
ExpectedAttributes = new Dictionary<string, string>(1)
{
{ "attribute-key", "attribute-value" },
};
}
public InMemoryDiagnosticLogger DiagnosticLogger { get; }
public IHub Hub { get; }
public SentryOptions Options { get; }
public ISystemClock Clock { get; }
public int BatchSize { get; set; }
public TimeSpan BatchTimeout { get; set; }
public SentryId TraceId { get; private set; }
public SpanId? SpanId { get; private set; }
public Dictionary<string, string> ExpectedAttributes { get; }
public void WithoutActiveSpan()
{
Hub.GetSpan().Returns((ISpan?)null);
var scope = new Scope();
Hub.SubstituteConfigureScope(scope);
TraceId = scope.PropagationContext.TraceId;
SpanId = null;
}
public SentryStructuredLogger GetSut() => SentryStructuredLogger.Create(Hub, Options, Clock, BatchSize, BatchTimeout);
}
private readonly Fixture _fixture;
public SentryStructuredLoggerTests()
{
_fixture = new Fixture();
}
public void Dispose()
{
_fixture.DiagnosticLogger.Entries.Should().BeEmpty();
}
[Fact]
public void Create_Enabled_NewDefaultInstance()
{
_fixture.Options.EnableLogs = true;
var instance = _fixture.GetSut();
var other = _fixture.GetSut();
instance.Should().BeOfType<DefaultSentryStructuredLogger>();
instance.Should().NotBeSameAs(other);
}
[Fact]
public void Create_Disabled_CachedDisabledInstance()
{
_fixture.Options.EnableLogs.Should().BeFalse();
var instance = _fixture.GetSut();
var other = _fixture.GetSut();
instance.Should().BeOfType<DisabledSentryStructuredLogger>();
instance.Should().BeSameAs(other);
}
[Fact]
public void Log_WithoutActiveSpan_CapturesEnvelope()
{
_fixture.WithoutActiveSpan();
_fixture.Options.EnableLogs = true;
var logger = _fixture.GetSut();
Envelope envelope = null!;
_fixture.Hub.CaptureEnvelope(Arg.Do<Envelope>(arg => envelope = arg));
logger.LogTrace(ConfigureLog, "Template string with arguments: {0}, {1}, {2}, {3}", "string", true, 1, 2.2);
logger.Flush();
_fixture.Hub.Received(1).CaptureEnvelope(Arg.Any<Envelope>());
_fixture.AssertEnvelope(envelope, SentryLogLevel.Trace);
}
[Fact]
public void Log_WithBeforeSendLog_InvokesCallback()
{
var invocations = 0;
SentryLog configuredLog = null!;
_fixture.Options.EnableLogs = true;
_fixture.Options.SetBeforeSendLog((SentryLog log) =>
{
invocations++;
configuredLog = log;
return log;
});
var logger = _fixture.GetSut();
logger.LogTrace(ConfigureLog, "Template string with arguments: {0}, {1}, {2}, {3}", "string", true, 1, 2.2);
logger.Flush();
_fixture.Hub.Received(1).CaptureEnvelope(Arg.Any<Envelope>());
invocations.Should().Be(1);
_fixture.AssertLog(configuredLog, SentryLogLevel.Trace);
}
[Fact]
public void Log_WhenBeforeSendLogReturnsNull_DoesNotCaptureEnvelope()
{
var invocations = 0;
_fixture.Options.EnableLogs = true;
_fixture.Options.SetBeforeSendLog((SentryLog log) =>
{
invocations++;
return null;
});
var logger = _fixture.GetSut();
logger.LogTrace(ConfigureLog, "Template string with arguments: {0}, {1}, {2}, {3}", "string", true, 1, 2.2);
_fixture.Hub.Received(0).CaptureEnvelope(Arg.Any<Envelope>());
invocations.Should().Be(1);
}
[Fact]
public void Log_InvalidFormat_DoesNotCaptureEnvelope()
{
_fixture.Options.EnableLogs = true;
var logger = _fixture.GetSut();
logger.LogTrace("Template string with arguments: {0}, {1}, {2}, {3}, {4}", "string", true, 1, 2.2);
_fixture.Hub.Received(0).CaptureEnvelope(Arg.Any<Envelope>());
var entry = _fixture.DiagnosticLogger.Dequeue();
entry.Level.Should().Be(SentryLevel.Error);
entry.Message.Should().Be("Template string does not match the provided argument. The Log will be dropped.");
entry.Exception.Should().BeOfType<FormatException>();
entry.Args.Should().BeEmpty();
}
[Fact]
public void Log_InvalidConfigureLog_DoesNotCaptureEnvelope()
{
_fixture.Options.EnableLogs = true;
var logger = _fixture.GetSut();
logger.LogTrace(static (SentryLog log) => throw new InvalidOperationException(), "Template string with arguments: {0}, {1}, {2}, {3}", "string", true, 1, 2.2);
_fixture.Hub.Received(0).CaptureEnvelope(Arg.Any<Envelope>());
var entry = _fixture.DiagnosticLogger.Dequeue();
entry.Level.Should().Be(SentryLevel.Error);
entry.Message.Should().Be("The configureLog callback threw an exception. The Log will be dropped.");
entry.Exception.Should().BeOfType<InvalidOperationException>();
entry.Args.Should().BeEmpty();
}
[Fact]
public void Log_InvalidBeforeSendLog_DoesNotCaptureEnvelope()
{
_fixture.Options.EnableLogs = true;
_fixture.Options.SetBeforeSendLog(static (SentryLog log) => throw new InvalidOperationException());
var logger = _fixture.GetSut();
logger.LogTrace("Template string with arguments: {0}, {1}, {2}, {3}", "string", true, 1, 2.2);
_fixture.Hub.Received(0).CaptureEnvelope(Arg.Any<Envelope>());
var entry = _fixture.DiagnosticLogger.Dequeue();
entry.Level.Should().Be(SentryLevel.Error);
entry.Message.Should().Be("The BeforeSendLog callback threw an exception. The Log will be dropped.");
entry.Exception.Should().BeOfType<InvalidOperationException>();
entry.Args.Should().BeEmpty();
}
[Fact]
public void Flush_AfterLog_CapturesEnvelope()
{
_fixture.Options.EnableLogs = true;
var logger = _fixture.GetSut();
Envelope envelope = null!;
_fixture.Hub.CaptureEnvelope(Arg.Do<Envelope>(arg => envelope = arg));
logger.Flush();
_fixture.Hub.Received(0).CaptureEnvelope(Arg.Any<Envelope>());
envelope.Should().BeNull();
logger.LogTrace(ConfigureLog, "Template string with arguments: {0}, {1}, {2}, {3}", "string", true, 1, 2.2);
_fixture.Hub.Received(0).CaptureEnvelope(Arg.Any<Envelope>());
envelope.Should().BeNull();
logger.Flush();
_fixture.Hub.Received(1).CaptureEnvelope(Arg.Any<Envelope>());
_fixture.AssertEnvelope(envelope, SentryLogLevel.Trace);
}
[Fact]
public void Dispose_BeforeLog_DoesNotCaptureEnvelope()
{
_fixture.Options.EnableLogs = true;
var logger = _fixture.GetSut();
var defaultLogger = logger.Should().BeOfType<DefaultSentryStructuredLogger>().Which;
defaultLogger.Dispose();
logger.LogTrace(ConfigureLog, "Template string with arguments: {0}, {1}, {2}, {3}", "string", true, 1, 2.2);
_fixture.Hub.Received(0).CaptureEnvelope(Arg.Any<Envelope>());
var entry = _fixture.DiagnosticLogger.Dequeue();
entry.Level.Should().Be(SentryLevel.Info);
entry.Message.Should().Be("{0}-Buffer full ... dropping {0}");
entry.Exception.Should().BeNull();
entry.Args.Should().BeEquivalentTo([nameof(SentryLog)]);
}
private static void ConfigureLog(SentryLog log)
{
log.SetAttribute("attribute-key", "attribute-value");
}
}
internal static class LoggerAssertionExtensions
{
public static void AssertEnvelope(this SentryStructuredLoggerTests.Fixture fixture, Envelope envelope, SentryLogLevel level)
{
envelope.Header.Should().ContainSingle().Which.Key.Should().Be("sdk");
var item = envelope.Items.Should().ContainSingle().Which;
var log = item.Payload.Should().BeOfType<JsonSerializable>().Which.Source.Should().BeOfType<StructuredLog>().Which;
AssertLog(fixture, log, level);
Assert.Collection(item.Header,
element => Assert.Equal(CreateHeader("type", "log"), element),
element => Assert.Equal(CreateHeader("item_count", 1), element),
element => Assert.Equal(CreateHeader("content_type", "application/vnd.sentry.items.log+json"), element));
}
public static void AssertEnvelopeWithoutAttributes(this SentryStructuredLoggerTests.Fixture fixture, Envelope envelope, SentryLogLevel level)
{
fixture.ExpectedAttributes.Clear();
AssertEnvelope(fixture, envelope, level);
}
public static void AssertLog(this SentryStructuredLoggerTests.Fixture fixture, StructuredLog log, SentryLogLevel level)
{
var items = log.Items;
items.Length.Should().Be(1);
AssertLog(fixture, items[0], level);
}
public static void AssertLog(this SentryStructuredLoggerTests.Fixture fixture, SentryLog log, SentryLogLevel level)
{
log.Timestamp.Should().Be(fixture.Clock.GetUtcNow());
log.TraceId.Should().Be(fixture.TraceId);
log.Level.Should().Be(level);
log.Message.Should().Be("Template string with arguments: string, True, 1, 2.2");
log.Template.Should().Be("Template string with arguments: {0}, {1}, {2}, {3}");
log.Parameters.Should().BeEquivalentTo(new KeyValuePair<string, object>[] { new("0", "string"), new("1", true), new("2", 1), new("3", 2.2), });
log.SpanId.Should().Be(fixture.SpanId);
foreach (var expectedAttribute in fixture.ExpectedAttributes)
{
log.TryGetAttribute(expectedAttribute.Key, out string? value).Should().BeTrue();
value.Should().Be(expectedAttribute.Value);
}
}
private static KeyValuePair<string, object?> CreateHeader(string name, object? value)
{
return new KeyValuePair<string, object?>(name, value);
}
public static SentryLog ShouldContainSingleLog(this Envelope envelope)
{
var envelopeItem = envelope.Items.Should().ContainSingle().Which;
var serializable = envelopeItem.Payload.Should().BeOfType<JsonSerializable>().Which;
var log = serializable.Source.Should().BeOfType<StructuredLog>().Which;
log.Items.Length.Should().Be(1);
return log.Items[0];
}
}