Skip to content

Commit df9fac6

Browse files
authored
Code Quality: Use lock statements in FileLogger (#16311)
1 parent dc5531d commit df9fac6

File tree

1 file changed

+12
-18
lines changed

1 file changed

+12
-18
lines changed

src/Files.Shared/Utils/Logger/FileLogger.cs

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,12 @@
66
using System.Diagnostics;
77
using System.IO;
88
using System.Linq;
9-
using System.Threading;
109

1110
namespace 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,48 +33,43 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
3433
{
3534
if (formatter is null)
3635
return;
37-
semaphoreSlim.Wait();
3836

3937
try
4038
{
4139
var message = exception?.ToString() ?? formatter(state, exception);
4240

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+
}
4445
}
4546
catch (Exception e)
4647
{
4748
Debug.WriteLine($"Writing to log file failed with the following exception:\n{e}");
4849
}
49-
finally
50-
{
51-
semaphoreSlim.Release();
52-
}
5350
}
5451

5552
public void PurgeLogs(int numberOfLinesKept)
5653
{
5754
if (!File.Exists(filePath))
5855
return;
5956

60-
semaphoreSlim.Wait();
61-
6257
try
6358
{
64-
var lines = File.ReadAllLines(filePath);
65-
if (lines.Length > numberOfLinesKept)
59+
lock (syncRoot)
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+
}
6967
}
7068
}
7169
catch (Exception e)
7270
{
7371
Debug.WriteLine($"Purging the log file failed with the following exception:\n{e}");
7472
}
75-
finally
76-
{
77-
semaphoreSlim.Release();
78-
}
7973
}
8074
}
8175
}

0 commit comments

Comments
 (0)