Skip to content

Commit d2bc586

Browse files
committed
Update FileLogger.cs
1 parent ef048b2 commit d2bc586

File tree

1 file changed

+23
-29
lines changed

1 file changed

+23
-29
lines changed

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

Lines changed: 23 additions & 29 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,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

Comments
 (0)