66using System . Diagnostics ;
77using System . IO ;
88using System . Linq ;
9- using System . Threading ;
109
1110namespace Files . Shared
1211{
1312 public sealed class FileLogger : ILogger
1413 {
15- private readonly SemaphoreSlim semaphoreSlim = new ( 1 ) ;
14+ private readonly object syncRoot = new ( ) ;
1615 private readonly string filePath ;
1716
1817 public FileLogger ( string filePath )
@@ -34,21 +33,19 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
3433 {
3534 if ( formatter is null )
3635 return ;
37- semaphoreSlim . Wait ( ) ;
3836
39- try
37+ lock ( syncRoot )
4038 {
41- var message = exception ? . ToString ( ) ?? formatter ( state , exception ) ;
39+ try
40+ {
41+ var message = exception ? . ToString ( ) ?? formatter ( state , exception ) ;
4242
43- File . AppendAllText ( filePath , $ "{ DateTime . Now : yyyy-MM-dd HH:mm:ss.ffff} |{ logLevel } |{ message } " + Environment . NewLine ) ;
44- }
45- catch ( Exception e )
46- {
47- Debug . WriteLine ( $ "Writing to log file failed with the following exception:\n { e } ") ;
48- }
49- finally
50- {
51- semaphoreSlim . Release ( ) ;
43+ File . AppendAllText ( filePath , $ "{ DateTime . Now : yyyy-MM-dd HH:mm:ss.ffff} |{ logLevel } |{ message } " + Environment . NewLine ) ;
44+ }
45+ catch ( Exception e )
46+ {
47+ Debug . WriteLine ( $ "Writing to log file failed with the following exception:\n { e } ") ;
48+ }
5249 }
5350 }
5451
@@ -57,24 +54,21 @@ public void PurgeLogs(int numberOfLinesKept)
5754 if ( ! File . Exists ( filePath ) )
5855 return ;
5956
60- semaphoreSlim . Wait ( ) ;
61-
62- try
57+ lock ( syncRoot )
6358 {
64- var lines = File . ReadAllLines ( filePath ) ;
65- if ( lines . Length > numberOfLinesKept )
59+ try
6660 {
67- var lastLines = lines . Skip ( Math . Max ( 0 , lines . Length - numberOfLinesKept ) ) ;
68- File . WriteAllLines ( filePath , lastLines ) ;
61+ var lines = File . ReadAllLines ( filePath ) ;
62+ if ( lines . Length > numberOfLinesKept )
63+ {
64+ var lastLines = lines . Skip ( Math . Max ( 0 , lines . Length - numberOfLinesKept ) ) ;
65+ File . WriteAllLines ( filePath , lastLines ) ;
66+ }
67+ }
68+ catch ( Exception e )
69+ {
70+ Debug . WriteLine ( $ "Purging the log file failed with the following exception:\n { e } ") ;
6971 }
70- }
71- catch ( Exception e )
72- {
73- Debug . WriteLine ( $ "Purging the log file failed with the following exception:\n { e } ") ;
74- }
75- finally
76- {
77- semaphoreSlim . Release ( ) ;
7872 }
7973 }
8074 }
0 commit comments