comparison 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
comparison
equal deleted inserted replaced
-1:000000000000 0:3e1a2131f897
1 using System;
2 using System.Collections.Generic;
3 using System.IO;
4 using System.Linq;
5 using System.Reflection;
6 using System.Text;
7 using System.Threading.Tasks;
8
9 namespace ServerMonitorApp
10 {
11 public class Logger
12 {
13 private const int logVersion = 1;
14 private readonly string logFile;
15
16 public Logger(string file)
17 {
18 logFile = file;
19 }
20
21 public async void Log(string logString)
22 {
23 if (!File.Exists(logFile))
24 logString = "Server Monitor log version " + logVersion + Environment.NewLine + logString;
25 using (FileStream stream = new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.Read, 4096, true))
26 using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
27 {
28 await writer.WriteLineAsync(logString);
29 }
30 }
31
32 public void Log(CheckResult result)
33 {
34 Log(result.ToLogString());
35 }
36
37 public IList<CheckResult> Read(Server server)
38 {
39 Dictionary<int, Check> checks = server.Checks.ToDictionary(c => c.Id);
40 List<CheckResult> results = new List<CheckResult>();
41 using (FileStream stream = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.Read))
42 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
43 {
44 while (true)
45 {
46 try
47 {
48 string line = reader.ReadLine();
49 if (line == null)
50 break;
51 if (int.TryParse(line.Substring(0, 5), out int id) && checks.TryGetValue(id, out Check check))
52 {
53 results.Add(CheckResult.FromLogString(check, line));
54 }
55 }
56 catch (Exception) { }
57 }
58 }
59 results.Reverse();
60 return results;
61 }
62 }
63 }