diff ServerMonitor/Objects/Logger.cs @ 6:c1dffaac66fa

- Don't show multiple password dialogs for the same key if the first one was cancelled. - Add option to trim log files.
author Brad Greco <brad@bgreco.net>
date Fri, 01 Mar 2019 21:38:22 -0500
parents 3e1a2131f897
children 7127d5b5ac75
line wrap: on
line diff
--- a/ServerMonitor/Objects/Logger.cs	Thu Feb 28 21:19:32 2019 -0500
+++ b/ServerMonitor/Objects/Logger.cs	Fri Mar 01 21:38:22 2019 -0500
@@ -1,4 +1,5 @@
-using System;
+using ServerMonitorApp.Properties;
+using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
@@ -59,5 +60,33 @@
             results.Reverse();
             return results;
         }
+
+        public async void TrimLog()
+        {
+            DateTime maxAge = DateTime.Now.AddDays(-1 * Settings.Default.KeepLogDays);
+            string tempFile = logFile + ".tmp";
+            using (FileStream stream = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.Read))
+            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
+            using (FileStream outStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
+            using (StreamWriter writer = new StreamWriter(outStream, Encoding.UTF8))
+            {
+                while (true)
+                {
+                    try
+                    {
+                        string line = reader.ReadLine();
+                        if (line == null)
+                            break;
+                        if (DateTime.TryParse(line.Substring(6, 10), out DateTime date) && date > maxAge)
+                        {
+                            await writer.WriteLineAsync(line);
+                        }
+                    }
+                    catch (Exception) { }
+                }
+            }
+            File.Delete(logFile);
+            File.Move(tempFile, logFile);
+        }
     }
 }