-
Notifications
You must be signed in to change notification settings - Fork 499
Expand file tree
/
Copy pathLoggingTests.cs
More file actions
690 lines (576 loc) · 26.3 KB
/
LoggingTests.cs
File metadata and controls
690 lines (576 loc) · 26.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
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
using Amazon.Lambda.Logging.AspNetCore.Tests;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Xunit;
namespace Amazon.Lambda.Tests
{
public class LoggingTests
{
private const string SHOULD_APPEAR = "TextThatShouldAppear";
private const string SHOULD_NOT_APPEAR = "TextThatShouldNotAppear";
private const string SHOULD_APPEAR_EVENT = "EventThatShouldAppear";
private const string SHOULD_APPEAR_EXCEPTION = "ExceptionThatShouldAppear";
private static string APPSETTINGS_DIR = Directory.GetCurrentDirectory();
private static readonly Func<int, EventId> GET_SHOULD_APPEAR_EVENT = (id) => new EventId(451, SHOULD_APPEAR_EVENT + id);
private static readonly EventId SHOULD_NOT_APPEAR_EVENT = new EventId(333, "EventThatShoulNotdAppear");
private static readonly Func<int, Exception> GET_SHOULD_APPEAR_EXCEPTION = (id) => new Exception(SHOULD_APPEAR_EXCEPTION + id);
private static readonly Exception SHOULD_NOT_APPEAR_EXCEPTION = new Exception("ExceptionThatShouldNotAppear");
[Fact]
public void TestConfiguration()
{
using (var writer = new StringWriter())
{
ConnectLoggingActionToLogger(message => writer.Write(message));
var configuration = new ConfigurationBuilder()
.AddJsonFile(GetAppSettingsPath("appsettings.json"))
.Build();
var loggerOptions = new LambdaLoggerOptions(configuration);
Assert.False(loggerOptions.IncludeCategory);
Assert.False(loggerOptions.IncludeLogLevel);
Assert.False(loggerOptions.IncludeNewline);
var loggerfactory = new TestLoggerFactory()
.AddLambdaLogger(loggerOptions);
int count = 0;
var defaultLogger = loggerfactory.CreateLogger("Default");
defaultLogger.LogTrace(SHOULD_NOT_APPEAR);
defaultLogger.LogDebug(SHOULD_APPEAR + (count++));
defaultLogger.LogCritical(SHOULD_APPEAR + (count++));
defaultLogger = loggerfactory.CreateLogger(null);
defaultLogger.LogTrace(SHOULD_NOT_APPEAR);
defaultLogger.LogDebug(SHOULD_APPEAR + (count++));
defaultLogger.LogCritical(SHOULD_APPEAR + (count++));
// change settings
int countAtChange = count;
loggerOptions.IncludeCategory = true;
loggerOptions.IncludeLogLevel = true;
loggerOptions.IncludeNewline = true;
var msLogger = loggerfactory.CreateLogger("Microsoft");
msLogger.LogTrace(SHOULD_NOT_APPEAR);
msLogger.LogInformation(SHOULD_APPEAR + (count++));
msLogger.LogCritical(SHOULD_APPEAR + (count++));
var sdkLogger = loggerfactory.CreateLogger("AWSSDK");
sdkLogger.LogTrace(SHOULD_NOT_APPEAR);
sdkLogger.LogInformation(SHOULD_APPEAR + (count++));
sdkLogger.LogCritical(SHOULD_APPEAR + (count++));
// get text and verify
var text = writer.ToString();
// check that there are no unexpected strings in the text
Assert.DoesNotContain(SHOULD_NOT_APPEAR, text);
// Confirm log level was written to log
Assert.Contains("Critical:", text);
// check that all expected strings are in the text
for (int i = 0; i < count; i++)
{
var expected = SHOULD_APPEAR + i;
Assert.True(text.Contains(expected), $"Expected to find '{expected}' in '{text}'");
}
// check extras that were added mid-way
int numberOfExtraBits = count - countAtChange;
// count levels
var logLevelStrings = Enum.GetNames(typeof(LogLevel)).Select(ll => $"[{ll}").ToList();
Assert.Equal(numberOfExtraBits, CountMultipleOccurences(text, logLevelStrings));
// count categories
var categoryStrings = new string[] { "Microsoft", "AWSSDK" };
Assert.Equal(numberOfExtraBits, CountMultipleOccurences(text, categoryStrings));
// count newlines
Assert.Equal(numberOfExtraBits, CountOccurences(text, Environment.NewLine));
}
}
[Fact]
public void TestWilcardConfiguration()
{
using (var writer = new StringWriter())
{
ConnectLoggingActionToLogger(message => writer.Write(message));
var configuration = new ConfigurationBuilder()
.AddJsonFile(GetAppSettingsPath("appsettings.wildcard.json"))
.Build();
var loggerOptions = new LambdaLoggerOptions(configuration);
Assert.False(loggerOptions.IncludeCategory);
Assert.False(loggerOptions.IncludeLogLevel);
Assert.False(loggerOptions.IncludeNewline);
var loggerFactory = new TestLoggerFactory()
.AddLambdaLogger(loggerOptions);
int count = 0;
// Should match:
// "Foo.*": "Information"
var foobarLogger = loggerFactory.CreateLogger("Foo.Bar");
foobarLogger.LogTrace(SHOULD_NOT_APPEAR);
foobarLogger.LogDebug(SHOULD_NOT_APPEAR);
foobarLogger.LogInformation(SHOULD_APPEAR + (count++));
foobarLogger.LogWarning(SHOULD_APPEAR + (count++));
foobarLogger.LogError(SHOULD_APPEAR + (count++));
foobarLogger.LogCritical(SHOULD_APPEAR + (count++));
// Should match:
// "Foo.Bar.Baz": "Critical"
var foobarbazLogger = loggerFactory.CreateLogger("Foo.Bar.Baz");
foobarbazLogger.LogTrace(SHOULD_NOT_APPEAR);
foobarbazLogger.LogDebug(SHOULD_NOT_APPEAR);
foobarbazLogger.LogInformation(SHOULD_NOT_APPEAR);
foobarbazLogger.LogWarning(SHOULD_NOT_APPEAR);
foobarbazLogger.LogError(SHOULD_NOT_APPEAR);
foobarbazLogger.LogCritical(SHOULD_APPEAR + (count++));
// Should match:
// "Foo.Bar.*": "Warning"
var foobarbuzzLogger = loggerFactory.CreateLogger("Foo.Bar.Buzz");
foobarbuzzLogger.LogTrace(SHOULD_NOT_APPEAR);
foobarbuzzLogger.LogDebug(SHOULD_NOT_APPEAR);
foobarbuzzLogger.LogInformation(SHOULD_NOT_APPEAR);
foobarbuzzLogger.LogWarning(SHOULD_APPEAR + (count++));
foobarbuzzLogger.LogError(SHOULD_APPEAR + (count++));
foobarbuzzLogger.LogCritical(SHOULD_APPEAR + (count++));
// Should match:
// "*": "Error"
var somethingLogger = loggerFactory.CreateLogger("something");
somethingLogger.LogTrace(SHOULD_NOT_APPEAR);
somethingLogger.LogDebug(SHOULD_NOT_APPEAR);
somethingLogger.LogInformation(SHOULD_NOT_APPEAR);
somethingLogger.LogWarning(SHOULD_NOT_APPEAR);
somethingLogger.LogError(SHOULD_APPEAR + (count++));
somethingLogger.LogCritical(SHOULD_APPEAR + (count++));
// get text and verify
var text = writer.ToString();
// check that there are no unexpected strings in the text
Assert.DoesNotContain(SHOULD_NOT_APPEAR, text);
// check that all expected strings are in the text
for (int i = 0; i < count; i++)
{
var expected = SHOULD_APPEAR + i;
Assert.True(text.Contains(expected), $"Expected to find '{expected}' in '{text}'");
}
}
}
[Fact]
public void TestOnlyOneWildcardSupported()
{
var dict = new Dictionary<string, string>
{
{ "Lambda.Logging:LogLevel:*.*", "Information" }
};
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(dict)
.Build();
ArgumentOutOfRangeException exception = null;
try
{
var loggerOptions = new LambdaLoggerOptions(configuration);
}
catch (ArgumentOutOfRangeException ex)
{
exception = ex;
}
// check that there are no unexpected strings in the text
Assert.NotNull(exception);
Assert.Contains("only 1 wildcard is supported in a category", exception.Message);
}
[Fact]
public void TestOnlyTerminatingWildcardsSupported()
{
var dict = new Dictionary<string, string>
{
{ "Lambda.Logging:LogLevel:Foo.*.Bar", "Information" }
};
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(dict)
.Build();
ArgumentException exception = null;
try
{
var loggerOptions = new LambdaLoggerOptions(configuration);
}
catch (ArgumentException ex)
{
exception = ex;
}
// check that there are no unexpected strings in the text
Assert.NotNull(exception);
Assert.Contains("wilcards are only supported at the end of a category", exception.Message);
}
[Fact]
public void TestConfigurationReadingForExceptionsEvents()
{
// Arrange
var configuration = new ConfigurationBuilder()
.AddJsonFile(GetAppSettingsPath("appsettings.exceptions.json"))
.Build();
// Act
var loggerOptions = new LambdaLoggerOptions(configuration);
// Assert
Assert.False(loggerOptions.IncludeCategory);
Assert.False(loggerOptions.IncludeLogLevel);
Assert.False(loggerOptions.IncludeNewline);
Assert.True(loggerOptions.IncludeEventId);
Assert.True(loggerOptions.IncludeException);
Assert.False(loggerOptions.IncludeScopes);
}
[Fact]
public void TestConfigurationReadingForScopes()
{
// Arrange
var configuration = new ConfigurationBuilder()
.AddJsonFile(GetAppSettingsPath("appsettings.scopes.json"))
.Build();
// Act
var loggerOptions = new LambdaLoggerOptions(configuration);
// Assert
Assert.False(loggerOptions.IncludeCategory);
Assert.False(loggerOptions.IncludeLogLevel);
Assert.False(loggerOptions.IncludeNewline);
Assert.True(loggerOptions.IncludeEventId);
Assert.True(loggerOptions.IncludeException);
Assert.True(loggerOptions.IncludeScopes);
}
[Fact]
public void TestLoggingExceptionsAndEvents()
{
using (var writer = new StringWriter())
{
ConnectLoggingActionToLogger(message => writer.Write(message));
var configuration = new ConfigurationBuilder()
.AddJsonFile(GetAppSettingsPath("appsettings.json"))
.Build();
var loggerOptions = new LambdaLoggerOptions(configuration);
var loggerFactory = new TestLoggerFactory()
.AddLambdaLogger(loggerOptions);
int countMessage = 0;
int countEvent = 0;
int countException = 0;
var defaultLogger = loggerFactory.CreateLogger("Default");
defaultLogger.LogTrace(SHOULD_NOT_APPEAR_EVENT, SHOULD_NOT_APPEAR_EXCEPTION, SHOULD_NOT_APPEAR);
defaultLogger.LogDebug(SHOULD_NOT_APPEAR_EVENT, SHOULD_APPEAR + (countMessage++));
defaultLogger.LogCritical(SHOULD_NOT_APPEAR_EVENT, SHOULD_APPEAR + (countMessage++));
defaultLogger = loggerFactory.CreateLogger(null);
defaultLogger.LogTrace(SHOULD_NOT_APPEAR_EVENT, SHOULD_NOT_APPEAR);
defaultLogger.LogDebug(SHOULD_NOT_APPEAR_EVENT, SHOULD_APPEAR + (countMessage++));
defaultLogger.LogCritical(SHOULD_NOT_APPEAR_EVENT, SHOULD_APPEAR + (countMessage++));
// change settings
loggerOptions.IncludeCategory = true;
loggerOptions.IncludeLogLevel = true;
loggerOptions.IncludeNewline = true;
loggerOptions.IncludeException = true;
loggerOptions.IncludeEventId = true;
var msLogger = loggerFactory.CreateLogger("Microsoft");
msLogger.LogTrace(SHOULD_NOT_APPEAR_EVENT, SHOULD_NOT_APPEAR_EXCEPTION, SHOULD_NOT_APPEAR);
msLogger.LogInformation(GET_SHOULD_APPEAR_EVENT(countEvent++), GET_SHOULD_APPEAR_EXCEPTION(countException++), SHOULD_APPEAR + (countMessage++));
msLogger.LogCritical(GET_SHOULD_APPEAR_EVENT(countEvent++), GET_SHOULD_APPEAR_EXCEPTION(countException++), SHOULD_APPEAR + (countMessage++));
var sdkLogger = loggerFactory.CreateLogger("AWSSDK");
sdkLogger.LogTrace(SHOULD_NOT_APPEAR_EVENT, SHOULD_NOT_APPEAR_EXCEPTION, SHOULD_NOT_APPEAR);
sdkLogger.LogInformation(GET_SHOULD_APPEAR_EVENT(countEvent++), GET_SHOULD_APPEAR_EXCEPTION(countException++), SHOULD_APPEAR + (countMessage++));
sdkLogger.LogCritical(GET_SHOULD_APPEAR_EVENT(countEvent++), GET_SHOULD_APPEAR_EXCEPTION(countException++), SHOULD_APPEAR + (countMessage++));
// get text and verify
var text = writer.ToString();
// check that there are no unexpected strings in the text
Assert.DoesNotContain(SHOULD_NOT_APPEAR, text);
Assert.DoesNotContain(SHOULD_NOT_APPEAR_EVENT.Id.ToString(), text);
Assert.DoesNotContain(SHOULD_NOT_APPEAR_EVENT.Name, text);
Assert.DoesNotContain(SHOULD_NOT_APPEAR_EXCEPTION.Message, text);
// check that all expected strings are in the text
for (int i = 0; i < countMessage; i++)
{
var expectedMessages = SHOULD_APPEAR + i;
Assert.True(text.Contains(expectedMessages), $"Expected to find '{expectedMessages}' in '{text}'");
}
for (int i = 0; i < countException; i++)
{
var expectedMessages = SHOULD_APPEAR_EXCEPTION + i;
Assert.True(text.Contains(expectedMessages), $"Expected to find '{expectedMessages}' in '{text}'");
}
for (int i = 0; i < countEvent; i++)
{
var expectedMessages = SHOULD_APPEAR_EVENT + i;
Assert.True(text.Contains(expectedMessages), $"Expected to find '{expectedMessages}' in '{text}'");
}
}
}
[Fact]
public void TestLoggingScopesEvents()
{
// Arrange
using (var writer = new StringWriter())
{
ConnectLoggingActionToLogger(message => writer.Write(message));
var loggerOptions = new LambdaLoggerOptions{ IncludeScopes = true };
var loggerFactory = new TestLoggerFactory()
.AddLambdaLogger(loggerOptions);
var defaultLogger = loggerFactory.CreateLogger("Default");
// Act
using(defaultLogger.BeginScope("First {0}", "scope123"))
{
defaultLogger.LogInformation("Hello");
using(defaultLogger.BeginScope("Second {0}", "scope456"))
{
defaultLogger.LogError("In 2nd scope");
defaultLogger.LogInformation("that's enough");
}
}
// Assert
// get text and verify
var text = writer.ToString();
Assert.Contains("[Information] First scope123 => Default: Hello ", text);
Assert.Contains("[Error] First scope123 Second scope456 => Default: In 2nd scope ", text);
Assert.Contains("[Information] First scope123 Second scope456 => Default: that's enough ", text);
}
}
[Fact]
public void TestLoggingScopesEvents_When_ScopesDisabled()
{
// Arrange
using (var writer = new StringWriter())
{
ConnectLoggingActionToLogger(message => writer.Write(message));
var loggerOptions = new LambdaLoggerOptions { IncludeScopes = false };
var loggerFactory = new TestLoggerFactory()
.AddLambdaLogger(loggerOptions);
var defaultLogger = loggerFactory.CreateLogger("Default");
// Act
using (defaultLogger.BeginScope("First {0}", "scope123"))
{
defaultLogger.LogInformation("Hello");
using (defaultLogger.BeginScope("Second {0}", "scope456"))
{
defaultLogger.LogError("In 2nd scope");
defaultLogger.LogInformation("that's enough");
}
}
// Assert
// get text and verify
var text = writer.ToString();
Assert.Contains("[Information] Default: Hello ", text);
Assert.Contains("[Error] Default: In 2nd scope ", text);
Assert.Contains("[Information] Default: that's enough ", text);
}
}
[Fact]
public void TestLoggingWithTypeCategories()
{
using (var writer = new StringWriter())
{
ConnectLoggingActionToLogger(message => writer.Write(message));
// arrange
var configuration = new ConfigurationBuilder()
.AddJsonFile(GetAppSettingsPath("appsettings.nsprefix.json"))
.Build();
var loggerOptions = new LambdaLoggerOptions(configuration);
var loggerFactory = new TestLoggerFactory()
.AddLambdaLogger(loggerOptions);
// act
var httpClientLogger = loggerFactory.CreateLogger<System.Net.HttpListener>();
var authMngrLogger = loggerFactory.CreateLogger<System.Net.AuthenticationManager>();
var arrayLogger = loggerFactory.CreateLogger<System.Array>();
httpClientLogger.LogTrace(SHOULD_NOT_APPEAR);
httpClientLogger.LogDebug(SHOULD_APPEAR);
httpClientLogger.LogInformation(SHOULD_APPEAR);
httpClientLogger.LogWarning(SHOULD_APPEAR);
httpClientLogger.LogError(SHOULD_APPEAR);
httpClientLogger.LogCritical(SHOULD_APPEAR);
authMngrLogger.LogTrace(SHOULD_NOT_APPEAR);
authMngrLogger.LogDebug(SHOULD_NOT_APPEAR);
authMngrLogger.LogInformation(SHOULD_APPEAR);
authMngrLogger.LogWarning(SHOULD_APPEAR);
authMngrLogger.LogError(SHOULD_APPEAR);
authMngrLogger.LogCritical(SHOULD_APPEAR);
arrayLogger.LogTrace(SHOULD_NOT_APPEAR);
arrayLogger.LogDebug(SHOULD_NOT_APPEAR);
arrayLogger.LogInformation(SHOULD_NOT_APPEAR);
arrayLogger.LogWarning(SHOULD_APPEAR);
arrayLogger.LogError(SHOULD_APPEAR);
arrayLogger.LogCritical(SHOULD_APPEAR);
// assert
var text = writer.ToString();
Assert.DoesNotContain(SHOULD_NOT_APPEAR, text);
}
}
[Fact]
public void TestDefaultLogLevel()
{
using (var writer = new StringWriter())
{
ConnectLoggingActionToLogger(message => writer.Write(message));
var configuration = new ConfigurationBuilder()
.AddJsonFile(GetAppSettingsPath("appsettings.json"))
.Build();
var loggerOptions = new LambdaLoggerOptions(configuration);
var loggerFactory = new TestLoggerFactory()
.AddLambdaLogger(loggerOptions);
// act
// creating named logger, `Default` category is set to "Debug"
// (Default category has special treatment - it's not actually stored, named logger just falls to default)
var defaultLogger = loggerFactory.CreateLogger("Default");
defaultLogger.LogTrace(SHOULD_NOT_APPEAR);
defaultLogger.LogDebug(SHOULD_APPEAR);
defaultLogger.LogInformation(SHOULD_APPEAR);
// `Dummy` category is not specified, we should use `Default` category instead
var dummyLogger = loggerFactory.CreateLogger("Dummy");
dummyLogger.LogTrace(SHOULD_NOT_APPEAR);
dummyLogger.LogDebug(SHOULD_APPEAR);
dummyLogger.LogInformation(SHOULD_APPEAR);
// `Microsoft` category is specified, log accordingly
var msLogger = loggerFactory.CreateLogger("Microsoft");
msLogger.LogTrace(SHOULD_NOT_APPEAR);
msLogger.LogDebug(SHOULD_NOT_APPEAR);
msLogger.LogInformation(SHOULD_APPEAR);
// assert
var text = writer.ToString();
Assert.DoesNotContain(SHOULD_NOT_APPEAR, text);
}
}
[Fact]
public void TestDefaultLogLevelIfNotConfigured()
{
// arrange
using (var writer = new StringWriter())
{
ConnectLoggingActionToLogger(message => writer.Write(message));
var configuration = new ConfigurationBuilder()
.AddJsonFile(GetAppSettingsPath("appsettings.without_default.json"))
.Build();
var loggerOptions = new LambdaLoggerOptions(configuration);
var loggerFactory = new TestLoggerFactory()
.AddLambdaLogger(loggerOptions);
// act
// `Dummy` category is not specified, we should stick with default: min level = INFO
var dummyLogger = loggerFactory.CreateLogger("Dummy");
dummyLogger.LogTrace(SHOULD_NOT_APPEAR);
dummyLogger.LogDebug(SHOULD_NOT_APPEAR);
dummyLogger.LogInformation(SHOULD_APPEAR);
// `Microsoft` category is specified, log accordingly
var msLogger = loggerFactory.CreateLogger("Microsoft");
msLogger.LogTrace(SHOULD_NOT_APPEAR);
msLogger.LogDebug(SHOULD_NOT_APPEAR);
msLogger.LogInformation(SHOULD_NOT_APPEAR);
// assert
var text = writer.ToString();
Assert.DoesNotContain(SHOULD_NOT_APPEAR, text);
}
}
/// <summary>
/// For this test we just need to make sure the _loggingWithLevelAndExceptionAction is called with parameters and exception.
/// We can't confirm the JSON formatting is done because RuntimeSupport is not involved. That is okay because we have
/// other tests that confirm RuntimeSupport formats the log as JSON. We jsut need to confirm the right callback is called
/// with the parameters from the log message.
/// </summary>
[Fact]
public void TestJSONParameterLogging()
{
Environment.SetEnvironmentVariable("AWS_LAMBDA_LOG_FORMAT", "JSON");
try
{
using (var writer = new StringWriter())
{
ConnectLoggingActionToLogger(message => writer.Write(message));
var configuration = new ConfigurationBuilder()
.AddJsonFile(GetAppSettingsPath("appsettings.json"))
.Build();
var loggerOptions = new LambdaLoggerOptions(configuration);
var loggerFactory = new TestLoggerFactory()
.AddLambdaLogger(loggerOptions);
var logger = loggerFactory.CreateLogger("JSONLogging");
logger.LogError(new Exception("Too Cheap"), "User {name} fail to by {product} for {price}", "Gilmour", "Guitar", 55.55);
var text = writer.ToString();
Assert.Contains("parameter count: 3", text);
Assert.Contains("Too Cheap", text);
}
}
finally
{
Environment.SetEnvironmentVariable("AWS_LAMBDA_LOG_FORMAT", null);
}
}
[Fact]
public void JsonLoggingWithNoOriginalFormat()
{
Environment.SetEnvironmentVariable("AWS_LAMBDA_LOG_FORMAT", "JSON");
try
{
using (var writer = new StringWriter())
{
ConnectLoggingActionToLogger(message => writer.Write(message));
var configuration = new ConfigurationBuilder()
.AddJsonFile(GetAppSettingsPath("appsettings.json"))
.Build();
var loggerOptions = new LambdaLoggerOptions(configuration);
var loggerFactory = new TestLoggerFactory()
.AddLambdaLogger(loggerOptions);
var logger = loggerFactory.CreateLogger("JSONLogging");
logger.Log(LogLevel.Error, new EventId(1), new Dictionary<string, object>() { { "Param1", "Value1" } }, null, (state, e) =>
{
var sb = new StringBuilder();
foreach(var kvp in state)
{
sb.AppendFormat("{0}:{1}\n", kvp.Key, kvp.Value);
}
return sb.ToString();
});
var text = writer.ToString();
Assert.Contains("Param1:Value1", text);
}
}
finally
{
Environment.SetEnvironmentVariable("AWS_LAMBDA_LOG_FORMAT", null);
}
}
private static string GetAppSettingsPath(string fileName)
{
return Path.Combine(APPSETTINGS_DIR, fileName);
}
private static void ConnectLoggingActionToLogger(Action<string> loggingAction)
{
var lambdaLoggerType = typeof(Amazon.Lambda.Core.LambdaLogger);
Assert.NotNull(lambdaLoggerType);
var loggingActionField = lambdaLoggerType
.GetTypeInfo()
.GetField("_loggingAction", BindingFlags.NonPublic | BindingFlags.Static);
Assert.NotNull(loggingActionField);
loggingActionField.SetValue(null, loggingAction);
Action<string, string, object[]> loggingWithLevelAction = (level, message, parameters) => {
var formattedMessage = $"{level}: {message}: parameter count: {parameters?.Length}";
loggingAction(formattedMessage);
};
var loggingWithLevelActionField = lambdaLoggerType
.GetTypeInfo()
.GetField("_loggingWithLevelAction", BindingFlags.NonPublic | BindingFlags.Static);
Assert.NotNull(loggingActionField);
loggingWithLevelActionField.SetValue(null, loggingWithLevelAction);
Action<string, Exception, string, object[]> loggingWithExceptionLevelAction = (level, exception, message, parameters) => {
var formattedMessage = $"{level}: {message}: parameter count: {parameters?.Length}\n{exception?.Message}";
loggingAction(formattedMessage);
};
var loggingWithExceptionLevelActionField = lambdaLoggerType
.GetTypeInfo()
.GetField("_loggingWithLevelAndExceptionAction", BindingFlags.NonPublic | BindingFlags.Static);
Assert.NotNull(loggingActionField);
loggingWithExceptionLevelActionField.SetValue(null, loggingWithExceptionLevelAction);
}
private static int CountOccurences(string text, string substring)
{
int occurences = 0;
int index = 0;
do
{
index = text.IndexOf(substring, index, StringComparison.Ordinal);
if (index >= 0)
{
occurences++;
index += substring.Length;
}
} while (index >= 0);
return occurences;
}
private static int CountMultipleOccurences(string text, IEnumerable<string> substrings)
{
int total = 0;
foreach (var substring in substrings)
{
total += CountOccurences(text, substring);
}
return total;
}
}
}