6
6
using System . Diagnostics ;
7
7
using System . IO ;
8
8
using System . Linq ;
9
- using System . Threading ;
10
9
11
10
namespace Files . Shared
12
11
{
13
12
public sealed class FileLogger : ILogger
14
13
{
15
- private readonly SemaphoreSlim semaphoreSlim = new ( 1 ) ;
14
+ private readonly object syncRoot = new ( ) ;
16
15
private readonly string filePath ;
17
16
18
17
public FileLogger ( string filePath )
@@ -34,48 +33,43 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
34
33
{
35
34
if ( formatter is null )
36
35
return ;
37
- semaphoreSlim . Wait ( ) ;
38
36
39
37
try
40
38
{
41
39
var message = exception ? . ToString ( ) ?? formatter ( state , exception ) ;
42
40
43
- File . AppendAllText ( filePath , $ "{ DateTime . Now : yyyy-MM-dd HH:mm:ss.ffff} |{ logLevel } |{ message } " + Environment . NewLine ) ;
41
+ lock ( syncRoot )
42
+ {
43
+ File . AppendAllText ( filePath , $ "{ DateTime . Now : yyyy-MM-dd HH:mm:ss.ffff} |{ logLevel } |{ message } " + Environment . NewLine ) ;
44
+ }
44
45
}
45
46
catch ( Exception e )
46
47
{
47
48
Debug . WriteLine ( $ "Writing to log file failed with the following exception:\n { e } ") ;
48
49
}
49
- finally
50
- {
51
- semaphoreSlim . Release ( ) ;
52
- }
53
50
}
54
51
55
52
public void PurgeLogs ( int numberOfLinesKept )
56
53
{
57
54
if ( ! File . Exists ( filePath ) )
58
55
return ;
59
56
60
- semaphoreSlim . Wait ( ) ;
61
-
62
57
try
63
58
{
64
- var lines = File . ReadAllLines ( filePath ) ;
65
- if ( lines . Length > numberOfLinesKept )
59
+ lock ( syncRoot )
66
60
{
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
+ }
69
67
}
70
68
}
71
69
catch ( Exception e )
72
70
{
73
71
Debug . WriteLine ( $ "Purging the log file failed with the following exception:\n { e } ") ;
74
72
}
75
- finally
76
- {
77
- semaphoreSlim . Release ( ) ;
78
- }
79
73
}
80
74
}
81
75
}
0 commit comments