Skip to content

Commit

Permalink
Create session-specific log files
Browse files Browse the repository at this point in the history
Updated BetterLogger to generate session-specific log filenames with timestamps. This approach ensures unique log files for each session and deletes old logs without removing the current session's log file.
  • Loading branch information
HakuSystems committed Nov 13, 2024
1 parent 61fdace commit defc7ad
Showing 1 changed file with 11 additions and 28 deletions.
39 changes: 11 additions & 28 deletions EasyExtractUnitypackageRework/EasyExtract/Utilities/BetterLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ namespace EasyExtract.Utilities;
public class BetterLogger
{
private static readonly object _lock = new();
private static readonly string SessionStartTime = DateTime.Now.ToString("yyyyMMdd_HHmmss");

public BetterLogger()
{
Expand All @@ -20,12 +21,15 @@ private static void InitializeLogger()

Directory.CreateDirectory(logPath);

var logFileName = $"Log_{SessionStartTime}.txt";

Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File(Path.Combine(logPath, "Log.txt"), LogEventLevel.Information,
rollingInterval: RollingInterval.Day, shared: true)
.WriteTo.File(Path.Combine(logPath, logFileName), LogEventLevel.Information,
rollingInterval: RollingInterval.Infinite, shared: true)
.CreateLogger();

DeleteLogsFolderIfRequired();
}

Expand All @@ -37,27 +41,15 @@ private static void DeleteLogsFolderIfRequired()

if (!Directory.Exists(logPath))
Directory.CreateDirectory(logPath);
if (Directory.Exists(logPath))
return;

var logFiles = Directory.GetFiles(logPath);
if (GetLogFileCreationDate(logFiles) < DateTime.Now.AddDays(-7))
DeleteLogsFolder();
}

private static void DeleteLogsFolder()
{
var applicationPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"EasyExtract");
var logPath = Path.Combine(applicationPath, "Logs");
var currentLogFile = Path.Combine(logPath, $"Log_{SessionStartTime}.txt");
var filesToDelete = logFiles.Where(f => f != currentLogFile).ToArray();

if (!Directory.Exists(logPath))
Directory.CreateDirectory(logPath);

var logFiles = Directory.GetFiles(logPath);
foreach (var logFile in logFiles)
if (FileNotBeingUsed(logFile))
File.Delete(logFile);
foreach (var file in filesToDelete)
if (FileNotBeingUsed(file))
File.Delete(file);
}

private static bool FileNotBeingUsed(string logFile)
Expand All @@ -73,15 +65,6 @@ private static bool FileNotBeingUsed(string logFile)
}
}

private static DateTime GetLogFileCreationDate(string[] logFiles)
{
if (logFiles.Length == 0)
return DateTime.Now;
var creationDates = logFiles.Select(logFile => File.GetCreationTime(logFile)).ToList();
return creationDates.Min();
}


public static Task LogAsync(string message, string source, Importance importance)
{
InitializeLogger();
Expand Down

0 comments on commit defc7ad

Please sign in to comment.