From d8a841907d04e2b478778dbfeafd91bc802f90c6 Mon Sep 17 00:00:00 2001 From: dnesov Date: Sun, 21 Jan 2024 18:12:42 +0100 Subject: [PATCH] Add log file limit to Logger. --- DaggerFramework/Source/Utils/Logger.cs | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/DaggerFramework/Source/Utils/Logger.cs b/DaggerFramework/Source/Utils/Logger.cs index d14c834..12d39d0 100644 --- a/DaggerFramework/Source/Utils/Logger.cs +++ b/DaggerFramework/Source/Utils/Logger.cs @@ -7,7 +7,12 @@ namespace DaggerFramework.Utils public class Logger { public static Action? OnLog; - public static string LogPath = "Logs/"; + public static string LogPath { get; set; } = "Logs/"; + + /// + /// Maximum amount of log files in a log folder. If it reaches the limit, all logs will be written to dagger-latest.log instead of creating a new one. + /// + public static int MaxLogFiles { get; set; } = 5; /// /// Specifies the logging level. In release builds, the log level is Error. In debug, the log level is Echo. @@ -24,9 +29,24 @@ namespace DaggerFramework.Utils if (WriteToFile && !_logCreated) { - Directory.CreateDirectory(LogPath); + var dirInfo = Directory.CreateDirectory(LogPath); + var files = dirInfo.GetFiles(); + string logName = $"dagger-{DateFormat}-{TimeFormat}.log".Replace(':', '.'); - _fileStream = File.Create(Path.Combine(LogPath, logName)); + + if (files.Length >= MaxLogFiles) + { + logName = "dagger-latest.log"; + } + + var path = Path.Combine(LogPath, logName); + + if (File.Exists(path)) + { + File.Delete(path); + } + + _fileStream = File.Create(path); _fileWriter = new StreamWriter(_fileStream); _logCreated = true; }