Repository navigation
Expand file tree
/
Copy pathLoggerServiceTests.cs
More file actions
954 lines (841 loc) · 40.9 KB
/
Copy pathLoggerServiceTests.cs
File metadata and controls
954 lines (841 loc) · 40.9 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
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using FolderDiffIL4DotNet.Common;
using FolderDiffIL4DotNet.Services;
using FolderDiffIL4DotNet.Tests.Helpers;
using Xunit;
namespace FolderDiffIL4DotNet.Tests.Services
{
[Collection("LoggerServiceTests NonParallel")]
[Trait("Category", "Unit")]
public sealed class LoggerServiceTests
{
[Fact]
public void Initialize_SetsLogFilePath_AndCreatesLogDirectory()
{
var logger = new LoggerService();
using var appDataScope = CreateAppDataOverrideScope();
try
{
logger.Initialize();
Assert.False(string.IsNullOrWhiteSpace(logger.LogFileAbsolutePath));
var directory = Path.GetDirectoryName(logger.LogFileAbsolutePath);
Assert.False(string.IsNullOrWhiteSpace(directory));
Assert.True(Directory.Exists(directory));
Assert.Equal(Path.GetFullPath(appDataScope.LogsRootAbsolutePath), directory);
var logFileName = Path.GetFileName(logger.LogFileAbsolutePath);
Assert.Matches(new Regex(@"^log_\d{8}\.log$", RegexOptions.CultureInvariant), logFileName);
var datePart = Assert.IsType<string>(logFileName)[4..^4];
Assert.True(
DateTime.TryParseExact(datePart, Constants.LOG_FILE_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None, out _),
$"Unexpected log file date format: {logFileName}");
}
finally
{
TryDeleteDirectory(appDataScope.RootAbsolutePath);
}
}
[Fact]
public void Initialize_WhenLocalApplicationDataOverrideIsEmpty_ThrowsInvalidOperationException()
{
var logger = new LoggerService();
using var appDataScope = CreateAppDataOverrideScope();
object? originalOverride = AppContext.GetData(AppDataPaths.LOCAL_APP_DATA_OVERRIDE_KEY);
try
{
AppContext.SetData(AppDataPaths.LOCAL_APP_DATA_OVERRIDE_KEY, string.Empty);
var ex = Assert.Throws<InvalidOperationException>(() => logger.Initialize());
Assert.Contains("LocalApplicationData", ex.Message, StringComparison.Ordinal);
Assert.Null(logger.LogFileAbsolutePath);
}
finally
{
AppContext.SetData(AppDataPaths.LOCAL_APP_DATA_OVERRIDE_KEY, originalOverride);
TryDeleteDirectory(appDataScope.RootAbsolutePath);
}
}
[Fact]
public void LogMessage_WithExplicitConsoleColor_WritesFormattedMessageAndFullExceptionDetailsToLogFile()
{
var logger = new LoggerService();
var originalOut = Console.Out;
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var tempLogPath = Path.Combine(tempDir, "log_test.log");
var writer = new StringWriter();
try
{
Console.SetOut(writer);
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", tempLogPath);
Exception captured;
try
{
throw new InvalidOperationException("boom");
}
catch (Exception ex)
{
captured = ex;
}
logger.LogMessage(AppLogLevel.Error, "failure", shouldOutputMessageToConsole: true, ConsoleColor.Red, captured);
var consoleText = writer.ToString();
Assert.Contains("[ERR] failure", consoleText);
var logText = File.ReadAllText(tempLogPath);
Assert.Contains("[ERR] failure", logText);
Assert.Contains(captured.ToString(), logText, StringComparison.Ordinal);
var firstLine = Assert.IsType<string>(logText.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)[0]);
Assert.Matches(new Regex(@"^\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}\] \[ERR\] failure$", RegexOptions.CultureInvariant), firstLine);
var timestampText = firstLine[1..firstLine.IndexOf(']')];
Assert.True(
DateTime.TryParseExact(timestampText, Constants.LOG_ENTRY_TIMESTAMP_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None, out _),
$"Unexpected log entry timestamp format: {firstLine}");
}
finally
{
Console.SetOut(originalOut);
try
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, recursive: true);
}
}
catch
{
// ignore cleanup errors / クリーンアップエラーを無視
}
}
}
[Fact]
public void LogMessage_DefaultOverload_KeepsExistingConsoleFormat()
{
var logger = new LoggerService();
var originalOut = Console.Out;
var writer = new StringWriter();
try
{
Console.SetOut(writer);
SetPrivateField(logger, "_logFileAbsolutePath", null);
logger.LogMessage(AppLogLevel.Info, "success", shouldOutputMessageToConsole: true);
var consoleText = writer.ToString();
Assert.Contains("[INF] success", consoleText);
}
finally
{
Console.SetOut(originalOut);
}
}
[Fact]
public void LogMessage_WhenNotInitialized_DoesNotWriteFile()
{
var logger = new LoggerService();
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", null);
try
{
logger.LogMessage(AppLogLevel.Info, "message", shouldOutputMessageToConsole: false);
Assert.Empty(Directory.GetFiles(tempDir));
}
finally
{
TryDeleteDirectory(tempDir);
}
}
[Fact]
public void CleanupOldLogFiles_DeletesOldFilesBeyondGenerationLimit()
{
var logger = new LoggerService();
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var old1 = Path.Combine(tempDir, "log_20240101.log");
var old2 = Path.Combine(tempDir, "log_20240102.log");
var keep = Path.Combine(tempDir, "log_20240103.log");
var active = Path.Combine(tempDir, "log_20991231.log");
File.WriteAllText(old1, "a");
File.WriteAllText(old2, "b");
File.WriteAllText(keep, "c");
File.WriteAllText(active, "d");
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", active);
try
{
logger.CleanupOldLogFiles(maxLogGenerations: 2);
Assert.False(File.Exists(old1));
Assert.False(File.Exists(old2));
Assert.True(File.Exists(keep));
Assert.True(File.Exists(active));
}
finally
{
TryDeleteDirectory(tempDir);
}
}
[Fact]
public void CleanupOldLogFiles_WhenUninitialized_ReturnsWithoutThrowing()
{
var logger = new LoggerService();
SetPrivateField(logger, "_logDirectoryAbsolutePath", null);
logger.CleanupOldLogFiles(1);
}
[Fact]
public void CleanupOldLogFiles_WithNegativeGeneration_DoesNotThrow()
{
var logger = new LoggerService();
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var active = Path.Combine(tempDir, "log_20991231.log");
File.WriteAllText(active, "active");
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", active);
try
{
logger.CleanupOldLogFiles(-1);
Assert.True(File.Exists(active));
}
finally
{
TryDeleteDirectory(tempDir);
}
}
// CleanupOldLogFiles catches UnauthorizedAccessException and continues when log directory is read-only (Linux/macOS non-root only)
// ログディレクトリが読み取り専用の場合、CleanupOldLogFiles は UnauthorizedAccessException をキャッチして継続する(Linux/macOS 非 root のみ)
[Fact]
public void CleanupOldLogFiles_ReadOnlyDirectory_LogsWarningAndDoesNotThrow()
{
if (!System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux)
&& !System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX))
{
return;
}
if (string.Equals(Environment.UserName, "root", StringComparison.OrdinalIgnoreCase))
{
return;
}
var logger = new LoggerService();
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
// Create multiple log files to exceed the generation limit
// ジェネレーション超過状態にするため複数のログファイルを作成する
var log1 = Path.Combine(tempDir, "log_20240101.log");
var log2 = Path.Combine(tempDir, "log_20240102.log");
var active = Path.Combine(tempDir, "log_20991231.log");
File.WriteAllText(log1, "a");
File.WriteAllText(log2, "b");
File.WriteAllText(active, "c");
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", active);
try
{
// Make directory read-only to prevent file deletion
// ディレクトリを読み取り専用にしてファイル削除を阻止
#pragma warning disable CA1416 // Unix-only API; test is skipped on Windows / Unix 専用 API; Windows ではテストがスキップされます
File.SetUnixFileMode(tempDir, UnixFileMode.UserRead | UnixFileMode.UserExecute);
#pragma warning restore CA1416
// Should catch IOException or UnauthorizedAccessException and continue
// IOException または UnauthorizedAccessException をキャッチして継続することを確認
var ex = Record.Exception(() => logger.CleanupOldLogFiles(maxLogGenerations: 1));
Assert.Null(ex);
}
finally
{
#pragma warning disable CA1416 // Unix-only API; test is skipped on Windows / Unix 専用 API; Windows ではテストがスキップされます
try { File.SetUnixFileMode(tempDir, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); } catch { }
#pragma warning restore CA1416
TryDeleteDirectory(tempDir);
}
}
[Fact]
public void CleanupOldLogFiles_WhenDirectoryPathIsActuallyAFile_LogsWarningWithExceptionTypeAndDoesNotThrow()
{
var logger = new LoggerService();
var originalOut = Console.Out;
using var writer = new StringWriter();
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var filePath = Path.Combine(tempDir, "not-a-directory.log");
File.WriteAllText(filePath, "x");
SetPrivateField(logger, "_logDirectoryAbsolutePath", filePath);
SetPrivateField(logger, "_logFileAbsolutePath", null);
try
{
Console.SetOut(writer);
var expected = Record.Exception(() => Directory.GetFiles(filePath, "log_*.log"));
Assert.NotNull(expected);
var ex = Record.Exception(() => logger.CleanupOldLogFiles(maxLogGenerations: 1));
Assert.Null(ex);
var consoleText = writer.ToString();
Assert.Contains("Failed to clean up old log files in", consoleText, StringComparison.Ordinal);
Assert.Contains(filePath, consoleText, StringComparison.Ordinal);
Assert.Contains("DirectoryIsPathRooted=True", consoleText, StringComparison.Ordinal);
Assert.Contains("DirectoryLooksPathLike=True", consoleText, StringComparison.Ordinal);
Assert.Contains("MaxGenerations=1", consoleText, StringComparison.Ordinal);
Assert.Contains("ActiveLog='(none)'", consoleText, StringComparison.Ordinal);
Assert.Contains("ActiveLogIsPathRooted=Unknown", consoleText, StringComparison.Ordinal);
Assert.Contains("ActiveLogLooksPathLike=False", consoleText, StringComparison.Ordinal);
Assert.Contains(expected.GetType().Name, consoleText, StringComparison.Ordinal);
Assert.Contains(expected.Message, consoleText, StringComparison.Ordinal);
}
finally
{
Console.SetOut(originalOut);
TryDeleteDirectory(tempDir);
}
}
/// <summary>
/// Verifies that concurrent LogMessage calls do not throw IOException.
/// 並列 LogMessage 呼び出しで IOException が発生しないことを検証する。
/// </summary>
[Fact]
public void LogMessage_ConcurrentCalls_DoNotThrow()
{
var logger = new LoggerService();
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var tempLogPath = Path.Combine(tempDir, "log_concurrent.log");
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", tempLogPath);
try
{
var ex = Record.Exception(() =>
{
Parallel.For(0, 100, i =>
{
logger.LogMessage(AppLogLevel.Info, $"Concurrent message {i}", shouldOutputMessageToConsole: false);
});
});
Assert.Null(ex);
var logText = File.ReadAllText(tempLogPath);
for (int i = 0; i < 100; i++)
{
Assert.Contains($"Concurrent message {i}", logText);
}
}
finally
{
TryDeleteDirectory(tempDir);
}
}
[Fact]
public void LogMessage_TextFormat_ReadOnlyExistingLogFile_AppendsWithoutThrowingOnWindows()
{
if (!OperatingSystem.IsWindows())
{
return;
}
var logger = new LoggerService();
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var tempLogPath = Path.Combine(tempDir, "log_readonly_text.log");
File.WriteAllText(tempLogPath, "existing");
File.SetAttributes(tempLogPath, File.GetAttributes(tempLogPath) | FileAttributes.ReadOnly);
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", tempLogPath);
try
{
var ex = Record.Exception(() => logger.LogMessage(AppLogLevel.Info, "after-readonly", shouldOutputMessageToConsole: false));
Assert.Null(ex);
var logText = File.ReadAllText(tempLogPath);
Assert.Contains("existing", logText, StringComparison.Ordinal);
Assert.Contains("after-readonly", logText, StringComparison.Ordinal);
}
finally
{
if (File.Exists(tempLogPath))
{
File.SetAttributes(tempLogPath, FileAttributes.Normal);
}
TryDeleteDirectory(tempDir);
}
}
[Fact]
public void LogMessage_JsonFormat_ReadOnlyExistingLogFile_AppendsWithoutThrowingOnWindows()
{
if (!OperatingSystem.IsWindows())
{
return;
}
var logger = new LoggerService { Format = LogFormat.Json };
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var tempLogPath = Path.Combine(tempDir, "log_readonly_json.log");
File.WriteAllText(tempLogPath, "{\"message\":\"existing\"}" + Environment.NewLine);
File.SetAttributes(tempLogPath, File.GetAttributes(tempLogPath) | FileAttributes.ReadOnly);
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", tempLogPath);
try
{
var ex = Record.Exception(() => logger.LogMessage(AppLogLevel.Warning, "json-after-readonly", shouldOutputMessageToConsole: false));
Assert.Null(ex);
var lines = File.ReadAllLines(tempLogPath);
Assert.Equal(2, lines.Length);
Assert.Contains("existing", lines[0], StringComparison.Ordinal);
Assert.Contains("json-after-readonly", lines[1], StringComparison.Ordinal);
}
finally
{
if (File.Exists(tempLogPath))
{
File.SetAttributes(tempLogPath, FileAttributes.Normal);
}
TryDeleteDirectory(tempDir);
}
}
[Fact]
public void LogMessage_InvalidLogFilePath_DoesNotThrow()
{
var logger = new LoggerService();
SetPrivateField(logger, "_logDirectoryAbsolutePath", Path.GetTempPath());
SetPrivateField(logger, "_logFileAbsolutePath", "\0invalid-log-path");
var ex = Record.Exception(() => logger.LogMessage(AppLogLevel.Info, "no-crash", shouldOutputMessageToConsole: false));
Assert.Null(ex);
}
// ── Mutation-testing additions / ミューテーションテスト追加 ──────────────
[Fact]
public void CleanupOldLogFiles_ExactlyAtMaxGenerations_NothingDeleted()
{
// When file count == maxLogGenerations, no files should be deleted
// ファイル数 == maxLogGenerations のとき、ファイルは削除されないこと
var logger = new LoggerService();
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var log1 = Path.Combine(tempDir, "log_20240101.log");
var log2 = Path.Combine(tempDir, "log_20240102.log");
var active = Path.Combine(tempDir, "log_20991231.log");
File.WriteAllText(log1, "a");
File.WriteAllText(log2, "b");
File.WriteAllText(active, "c");
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", active);
try
{
// 3 files, maxLogGenerations=3 → no deletion
// 3 ファイル、maxLogGenerations=3 → 削除なし
logger.CleanupOldLogFiles(maxLogGenerations: 3);
Assert.True(File.Exists(log1));
Assert.True(File.Exists(log2));
Assert.True(File.Exists(active));
}
finally
{
TryDeleteDirectory(tempDir);
}
}
[Fact]
public void CleanupOldLogFiles_FewerThanMaxGenerations_NothingDeleted()
{
// When file count < maxLogGenerations, no files should be deleted
// ファイル数 < maxLogGenerations のとき、ファイルは削除されないこと
var logger = new LoggerService();
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var active = Path.Combine(tempDir, "log_20991231.log");
File.WriteAllText(active, "a");
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", active);
try
{
// 1 file, maxLogGenerations=5 → no deletion
// 1 ファイル、maxLogGenerations=5 → 削除なし
logger.CleanupOldLogFiles(maxLogGenerations: 5);
Assert.True(File.Exists(active));
}
finally
{
TryDeleteDirectory(tempDir);
}
}
[Fact]
public void CleanupOldLogFiles_MaxGenerationsZero_PreservesActiveLogAndDeletesArchivedLogs()
{
var logger = new LoggerService();
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var archived1 = Path.Combine(tempDir, "log_20240101.log");
var archived2 = Path.Combine(tempDir, "log_20240102.log");
var active = Path.Combine(tempDir, "log_20991231.log");
File.WriteAllText(archived1, "a");
File.WriteAllText(archived2, "b");
File.WriteAllText(active, "active");
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", active);
try
{
logger.CleanupOldLogFiles(maxLogGenerations: 0);
Assert.False(File.Exists(archived1));
Assert.False(File.Exists(archived2));
Assert.True(File.Exists(active));
var logText = File.ReadAllText(active);
Assert.Contains("Deleted old log file", logText, StringComparison.Ordinal);
}
finally
{
TryDeleteDirectory(tempDir);
}
}
[Fact]
public void CleanupOldLogFiles_WithNegativeGeneration_LogsSingleReadableWarningMessage()
{
var logger = new LoggerService();
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var active = Path.Combine(tempDir, "log_20991231.log");
File.WriteAllText(active, "active");
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", active);
try
{
logger.CleanupOldLogFiles(-1);
var logText = File.ReadAllText(active);
Assert.Contains("ArgumentOutOfRangeException", logText, StringComparison.Ordinal);
Assert.Contains("MaxLogGenerations must be a non-negative integer.", logText, StringComparison.Ordinal);
Assert.DoesNotContain("integer..", logText, StringComparison.Ordinal);
Assert.Contains("maxLogGenerations", logText, StringComparison.Ordinal);
Assert.Contains("MaxGenerations=-1", logText, StringComparison.Ordinal);
Assert.Contains(active, logText, StringComparison.Ordinal);
}
finally
{
TryDeleteDirectory(tempDir);
}
}
[Fact]
public void CleanupOldLogFiles_ReadOnlyArchivedFile_DeletesItOnWindows()
{
if (!OperatingSystem.IsWindows())
{
return;
}
var logger = new LoggerService();
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var archived = Path.Combine(tempDir, "log_20240101.log");
var active = Path.Combine(tempDir, "log_20991231.log");
File.WriteAllText(archived, "archived");
File.WriteAllText(active, "active");
File.SetAttributes(archived, File.GetAttributes(archived) | FileAttributes.ReadOnly);
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", active);
try
{
logger.CleanupOldLogFiles(maxLogGenerations: 1);
Assert.False(File.Exists(archived));
Assert.True(File.Exists(active));
}
finally
{
if (File.Exists(archived))
{
File.SetAttributes(archived, FileAttributes.Normal);
}
TryDeleteDirectory(tempDir);
}
}
[Fact]
public void CleanupOldLogFiles_WhenOneDeletionFails_ContinuesDeletingOtherArchivedLogsOnWindows()
{
if (!OperatingSystem.IsWindows())
{
return;
}
var logger = new LoggerService();
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var lockedArchived = Path.Combine(tempDir, "log_20240101.log");
var deletableArchived = Path.Combine(tempDir, "log_20240102.log");
var active = Path.Combine(tempDir, "log_20991231.log");
File.WriteAllText(lockedArchived, "locked");
File.WriteAllText(deletableArchived, "delete-me");
File.WriteAllText(active, "active");
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", active);
using var lockStream = new FileStream(lockedArchived, FileMode.Open, FileAccess.Read, FileShare.None);
try
{
logger.CleanupOldLogFiles(maxLogGenerations: 1);
Assert.True(File.Exists(lockedArchived));
Assert.False(File.Exists(deletableArchived));
Assert.True(File.Exists(active));
var logText = File.ReadAllText(active);
Assert.Contains("Failed to delete archived log file", logText, StringComparison.Ordinal);
Assert.Contains(active, logText, StringComparison.Ordinal);
Assert.Contains("ArchivedLogIsPathRooted=True", logText, StringComparison.Ordinal);
Assert.Contains("ArchivedLogLooksPathLike=True", logText, StringComparison.Ordinal);
Assert.Contains("ActiveLogIsPathRooted=True", logText, StringComparison.Ordinal);
Assert.Contains("ActiveLogLooksPathLike=True", logText, StringComparison.Ordinal);
Assert.Contains("Deleted old log file", logText, StringComparison.Ordinal);
}
finally
{
lockStream.Dispose();
TryDeleteDirectory(tempDir);
}
}
[Fact]
public void TryWriteFileLoggingFailureToConsole_LogsPathLikeDiagnostics()
{
var originalError = Console.Error;
using var writer = new StringWriter();
var method = typeof(LoggerService).GetMethod("TryWriteFileLoggingFailureToConsole", BindingFlags.Static | BindingFlags.NonPublic);
Assert.NotNull(method);
const string relativeLogPath = "logs/relative-log.log";
try
{
Console.SetError(writer);
method.Invoke(null, [relativeLogPath, new InvalidOperationException("write failed")]);
var errorText = writer.ToString();
Assert.Contains($"Failed to write log file '{relativeLogPath}'", errorText, StringComparison.Ordinal);
Assert.Contains("LogFileIsPathRooted=False", errorText, StringComparison.Ordinal);
Assert.Contains("LogFileLooksPathLike=True", errorText, StringComparison.Ordinal);
Assert.Contains(nameof(InvalidOperationException), errorText, StringComparison.Ordinal);
Assert.Contains("write failed", errorText, StringComparison.Ordinal);
}
finally
{
Console.SetError(originalError);
}
}
[Fact]
public void FormatMessage_WhitespaceOnlyMessage_ReturnsPrefixOnly()
{
// When message is whitespace-only, FormatMessage should return just the prefix
// メッセージがホワイトスペースのみの場合、FormatMessage はプレフィックスのみを返す
var logger = new LoggerService();
var originalOut = Console.Out;
var writer = new StringWriter();
try
{
Console.SetOut(writer);
SetPrivateField(logger, "_logFileAbsolutePath", null);
logger.LogMessage(AppLogLevel.Info, " ", shouldOutputMessageToConsole: true);
var consoleText = writer.ToString();
// Should contain just the prefix without trailing whitespace message
// プレフィックスのみが含まれ、後続のホワイトスペースメッセージがないこと
Assert.Contains("[INF]", consoleText);
// The trimmed line should be exactly the prefix
// トリムされた行はプレフィックスのみであること
var trimmed = consoleText.Trim();
Assert.Equal("[INF]", trimmed);
}
finally
{
Console.SetOut(originalOut);
}
}
// -----------------------------------------------------------------------
// JSON log format / JSON ログ形式
// -----------------------------------------------------------------------
[Fact]
public void LogMessage_JsonFormat_WritesNdjsonToFile()
{
var logger = new LoggerService { Format = LogFormat.Json };
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var tempLogPath = Path.Combine(tempDir, "log_json_test.log");
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", tempLogPath);
try
{
logger.LogMessage(AppLogLevel.Info, "hello json", shouldOutputMessageToConsole: false);
Assert.True(File.Exists(tempLogPath));
var content = File.ReadAllText(tempLogPath).Trim();
var doc = System.Text.Json.JsonDocument.Parse(content);
var root = doc.RootElement;
Assert.True(root.TryGetProperty("timestamp", out _));
Assert.Equal("INFO", root.GetProperty("level").GetString());
Assert.Equal("hello json", root.GetProperty("message").GetString());
Assert.False(root.TryGetProperty("exceptionType", out _));
Assert.False(root.TryGetProperty("exceptionDetail", out _));
}
finally
{
TryDeleteDirectory(tempDir);
}
}
[Fact]
public void LogMessage_JsonFormat_IncludesExceptionFields()
{
var logger = new LoggerService { Format = LogFormat.Json };
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var tempLogPath = Path.Combine(tempDir, "log_json_exc.log");
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", tempLogPath);
try
{
Exception captured;
try { throw new InvalidOperationException("test-error"); }
catch (Exception ex) { captured = ex; }
logger.LogMessage(AppLogLevel.Error, "failure", shouldOutputMessageToConsole: false, captured);
var content = File.ReadAllText(tempLogPath).Trim();
var doc = System.Text.Json.JsonDocument.Parse(content);
var root = doc.RootElement;
Assert.Equal("ERROR", root.GetProperty("level").GetString());
Assert.Equal("failure", root.GetProperty("message").GetString());
Assert.Equal("System.InvalidOperationException", root.GetProperty("exceptionType").GetString());
Assert.Equal("test-error", root.GetProperty("exceptionMessage").GetString());
Assert.Contains("System.InvalidOperationException: test-error", root.GetProperty("exceptionDetail").GetString(), StringComparison.Ordinal);
Assert.True(root.TryGetProperty("stackTrace", out _));
}
finally
{
TryDeleteDirectory(tempDir);
}
}
[Fact]
public void LogMessage_JsonFormat_IncludesInnerExceptionFields()
{
var logger = new LoggerService { Format = LogFormat.Json };
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var tempLogPath = Path.Combine(tempDir, "log_json_inner_exc.log");
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", tempLogPath);
try
{
Exception captured;
try
{
throw new InvalidOperationException("outer-error", new IOException("inner-error"));
}
catch (Exception ex)
{
captured = ex;
}
logger.LogMessage(AppLogLevel.Error, "failure", shouldOutputMessageToConsole: false, captured);
var content = File.ReadAllText(tempLogPath).Trim();
var doc = System.Text.Json.JsonDocument.Parse(content);
var root = doc.RootElement;
Assert.Equal("System.IO.IOException", root.GetProperty("innerExceptionType").GetString());
Assert.Equal("inner-error", root.GetProperty("innerExceptionMessage").GetString());
Assert.Contains(" ---> System.IO.IOException: inner-error", root.GetProperty("exceptionDetail").GetString(), StringComparison.Ordinal);
}
finally
{
TryDeleteDirectory(tempDir);
}
}
[Fact]
public void LogMessage_JsonFormat_TimestampIsIso8601()
{
var logger = new LoggerService { Format = LogFormat.Json };
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var tempLogPath = Path.Combine(tempDir, "log_json_ts.log");
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", tempLogPath);
try
{
logger.LogMessage(AppLogLevel.Warning, "ts-check", shouldOutputMessageToConsole: false);
var content = File.ReadAllText(tempLogPath).Trim();
var doc = System.Text.Json.JsonDocument.Parse(content);
var tsStr = doc.RootElement.GetProperty("timestamp").GetString();
// ISO 8601 round-trip format / ISO 8601 ラウンドトリップ形式
Assert.True(
DateTimeOffset.TryParse(tsStr, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out _),
$"Timestamp '{tsStr}' is not a valid ISO 8601 format");
Assert.Equal("WARNING", doc.RootElement.GetProperty("level").GetString());
}
finally
{
TryDeleteDirectory(tempDir);
}
}
[Fact]
public void Format_DefaultIsText()
{
var logger = new LoggerService();
Assert.Equal(LogFormat.Text, logger.Format);
}
// -----------------------------------------------------------------------
// TraceId / JSON traceId and spanId fields
// トレース ID / JSON traceId・spanId フィールド
// -----------------------------------------------------------------------
[Fact]
public void TraceId_BeforeInitialization_IsNull()
{
var logger = new LoggerService();
Assert.Null(logger.TraceId);
}
[Fact]
public void TraceId_AfterInitialization_Is32HexChars()
{
var logger = new LoggerService();
using var appDataScope = CreateAppDataOverrideScope();
try
{
logger.Initialize();
Assert.NotNull(logger.TraceId);
Assert.Matches(new Regex(@"^[0-9a-f]{32}$", RegexOptions.CultureInvariant), logger.TraceId);
}
finally
{
TryDeleteDirectory(appDataScope.RootAbsolutePath);
}
}
[Fact]
public void LogMessage_JsonFormat_IncludesTraceIdAndSpanId()
{
var logger = new LoggerService { Format = LogFormat.Json };
var tempDir = Path.Combine(Path.GetTempPath(), "fd-logger-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
var tempLogPath = Path.Combine(tempDir, "log_json_trace.log");
using var appDataScope = CreateAppDataOverrideScope();
try
{
logger.Initialize();
SetPrivateField(logger, "_logDirectoryAbsolutePath", tempDir);
SetPrivateField(logger, "_logFileAbsolutePath", tempLogPath);
logger.LogMessage(AppLogLevel.Info, "trace-test", shouldOutputMessageToConsole: false);
var content = File.ReadAllText(tempLogPath).Trim();
var doc = System.Text.Json.JsonDocument.Parse(content);
var root = doc.RootElement;
// traceId should be a 32-char hex string matching the logger's TraceId
// traceId はロガーの TraceId と一致する 32 桁の 16 進文字列であること
var traceId = root.GetProperty("traceId").GetString();
Assert.Equal(logger.TraceId, traceId);
// spanId should be a 16-char hex string (W3C Trace Context format)
// spanId は 16 桁の 16 進文字列(W3C Trace Context 形式)であること
var spanId = root.GetProperty("spanId").GetString();
Assert.NotNull(spanId);
Assert.Matches(new Regex(@"^[0-9a-f]{16}$", RegexOptions.CultureInvariant), spanId);
}
finally
{
TryDeleteDirectory(tempDir);
TryDeleteDirectory(appDataScope.RootAbsolutePath);
}
}
private static AppDataOverrideScope CreateAppDataOverrideScope()
=> new(Path.Combine(Path.GetTempPath(), "fd-logger-appdata-" + Guid.NewGuid().ToString("N")));
private static void SetPrivateField(object target, string fieldName, string value)
{
var fieldInfo = target.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
Assert.NotNull(fieldInfo);
fieldInfo.SetValue(target, value);
}
private static void TryDeleteDirectory(string path)
{
try
{
if (Directory.Exists(path))
{
Directory.Delete(path, recursive: true);
}
}
catch
{
// ignore cleanup errors / クリーンアップエラーを無視
}
}
}
[CollectionDefinition("LoggerServiceTests NonParallel", DisableParallelization = true)]
public sealed class LoggerServiceTestCollectionDefinition
{
}
}