Mercurial > servermonitor
diff ServerMonitor/Objects/Logger.cs @ 0:3e1a2131f897
Initial commit. Ping check, scheduling, UI working. SSH check mostly working.
author | Brad Greco <brad@bgreco.net> |
---|---|
date | Mon, 31 Dec 2018 18:32:14 -0500 |
parents | |
children | c1dffaac66fa |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ServerMonitor/Objects/Logger.cs Mon Dec 31 18:32:14 2018 -0500 @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace ServerMonitorApp +{ + public class Logger + { + private const int logVersion = 1; + private readonly string logFile; + + public Logger(string file) + { + logFile = file; + } + + public async void Log(string logString) + { + if (!File.Exists(logFile)) + logString = "Server Monitor log version " + logVersion + Environment.NewLine + logString; + using (FileStream stream = new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.Read, 4096, true)) + using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8)) + { + await writer.WriteLineAsync(logString); + } + } + + public void Log(CheckResult result) + { + Log(result.ToLogString()); + } + + public IList<CheckResult> Read(Server server) + { + Dictionary<int, Check> checks = server.Checks.ToDictionary(c => c.Id); + List<CheckResult> results = new List<CheckResult>(); + using (FileStream stream = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.Read)) + using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) + { + while (true) + { + try + { + string line = reader.ReadLine(); + if (line == null) + break; + if (int.TryParse(line.Substring(0, 5), out int id) && checks.TryGetValue(id, out Check check)) + { + results.Add(CheckResult.FromLogString(check, line)); + } + } + catch (Exception) { } + } + } + results.Reverse(); + return results; + } + } +}