Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 12 additions & 18 deletions src/Files.Shared/Utils/Logger/FileLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -34,48 +33,43 @@ public void Log<TState>(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)
{
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();
}
}
}
}
Loading