diff --git a/src/Files.Shared/Utils/Logger/FileLogger.cs b/src/Files.Shared/Utils/Logger/FileLogger.cs index 5e4a5d52ca95..102ee94c15e9 100644 --- a/src/Files.Shared/Utils/Logger/FileLogger.cs +++ b/src/Files.Shared/Utils/Logger/FileLogger.cs @@ -6,13 +6,12 @@ using System.Diagnostics; using System.IO; using System.Linq; -using System.Threading; namespace Files.Shared { public sealed class FileLogger : ILogger { - private readonly SemaphoreSlim semaphoreSlim = new(1); + private readonly object syncRoot = new(); private readonly string filePath; public FileLogger(string filePath) @@ -34,22 +33,20 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except { if (formatter is null) return; - semaphoreSlim.Wait(); try { var message = exception?.ToString() ?? formatter(state, exception); - File.AppendAllText(filePath, $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.ffff}|{logLevel}|{message}" + Environment.NewLine); + lock (syncRoot) + { + File.AppendAllText(filePath, $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.ffff}|{logLevel}|{message}" + Environment.NewLine); + } } catch (Exception e) { Debug.WriteLine($"Writing to log file failed with the following exception:\n{e}"); } - finally - { - semaphoreSlim.Release(); - } } public void PurgeLogs(int numberOfLinesKept) @@ -57,25 +54,22 @@ public void PurgeLogs(int numberOfLinesKept) if (!File.Exists(filePath)) return; - semaphoreSlim.Wait(); - try { - var lines = File.ReadAllLines(filePath); - if (lines.Length > numberOfLinesKept) + lock (syncRoot) { - var lastLines = lines.Skip(Math.Max(0, lines.Length - numberOfLinesKept)); - File.WriteAllLines(filePath, lastLines); + var lines = File.ReadAllLines(filePath); + if (lines.Length > numberOfLinesKept) + { + var lastLines = lines.Skip(Math.Max(0, lines.Length - numberOfLinesKept)); + File.WriteAllLines(filePath, lastLines); + } } } catch (Exception e) { Debug.WriteLine($"Purging the log file failed with the following exception:\n{e}"); } - finally - { - semaphoreSlim.Release(); - } } } }