Mercurial > servermonitor
comparison ServerMonitor/Objects/Logger.cs @ 9:7127d5b5ac75
Code cleanup and comments
author | Brad Greco <brad@bgreco.net> |
---|---|
date | Mon, 08 Apr 2019 21:29:54 -0400 |
parents | c1dffaac66fa |
children | 68d7834dc28e |
comparison
equal
deleted
inserted
replaced
8:052aa62cb42a | 9:7127d5b5ac75 |
---|---|
63 | 63 |
64 public async void TrimLog() | 64 public async void TrimLog() |
65 { | 65 { |
66 DateTime maxAge = DateTime.Now.AddDays(-1 * Settings.Default.KeepLogDays); | 66 DateTime maxAge = DateTime.Now.AddDays(-1 * Settings.Default.KeepLogDays); |
67 string tempFile = logFile + ".tmp"; | 67 string tempFile = logFile + ".tmp"; |
68 using (FileStream stream = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.Read)) | 68 try |
69 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) | |
70 using (FileStream outStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None)) | |
71 using (StreamWriter writer = new StreamWriter(outStream, Encoding.UTF8)) | |
72 { | 69 { |
73 while (true) | 70 using (FileStream stream = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.Read)) |
71 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) | |
72 using (FileStream outStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None)) | |
73 using (StreamWriter writer = new StreamWriter(outStream, Encoding.UTF8)) | |
74 { | 74 { |
75 try | 75 while (true) |
76 { | 76 { |
77 string line = reader.ReadLine(); | 77 try |
78 if (line == null) | |
79 break; | |
80 if (DateTime.TryParse(line.Substring(6, 10), out DateTime date) && date > maxAge) | |
81 { | 78 { |
82 await writer.WriteLineAsync(line); | 79 string line = reader.ReadLine(); |
80 if (line == null) | |
81 break; | |
82 if (DateTime.TryParse(line.Substring(6, 10), out DateTime date) && date > maxAge) | |
83 { | |
84 await writer.WriteLineAsync(line); | |
85 } | |
83 } | 86 } |
87 catch (Exception) { } | |
84 } | 88 } |
85 catch (Exception) { } | |
86 } | 89 } |
90 File.Delete(logFile); | |
91 File.Move(tempFile, logFile); | |
87 } | 92 } |
88 File.Delete(logFile); | 93 catch (FileNotFoundException) |
89 File.Move(tempFile, logFile); | 94 { |
95 // Do nothing if the log file does not exist yet. | |
96 } | |
90 } | 97 } |
91 } | 98 } |
92 } | 99 } |