forked from RagingLightning/TSW2-Livery-Manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Log.cs
70 lines (64 loc) · 2.68 KB
/
Log.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
namespace TSW2LM
{
class Log
{
private static Dictionary<string, LogLevel> LogPaths = new Dictionary<string, LogLevel>();
/// <summary>The highest LogLevel shown on the Console</summary>
public static LogLevel ConsoleLevel = LogLevel.INFO;
/// <summary> Adds a log file to be written to</summary>
/// <param name="path">The path of the new log file, relative or absolute.</param>
/// <param name="level">The highest LogLevel that will be written to this file.</param>
/// <returns>true, if the file was added successfully, false, if the file was already added, only the level has been changed</returns>
/// <exception cref="IOException">There was an error accessing {path} in an attempt to add it as a level {level} log file.</exception>
public static bool AddLogFile(string path, LogLevel level)
{
if (LogPaths.ContainsKey(path))
{
LogPaths[path] = level;
return false;
}
try
{
File.OpenWrite(path).Close();
LogPaths.Add(path, level);
return true;
}
catch (Exception)
{
throw new IOException($"There was an error accessing {path} in an attempt to add it as a level {level} log file.");
}
}
/// <summary> Logs a message in the format "[<LEVEL>] <Time> <stack> | <message>"</summary>
/// <param name="message">The log message.</param>
/// <param name="stack">A simple string representation of the call stack</param>
/// <param name="level">The LogLevel of this message, it will only be logged to each file that has a LogLevel at or above that of the message</param>
public static void AddLogMessage(string message, string? stack = "-", LogLevel? level = LogLevel.INFO)
{
string Timestamp = DateTime.Now.ToString("MMddTHH:mm:ss.fff");
string LogLine = $"[{level.ToString()}] {Timestamp} {stack} | {message}\n";
if (ConsoleLevel >= level)
{
Trace.Write(LogLine);
Console.Write(LogLine);
}
foreach (KeyValuePair<string, LogLevel> p in LogPaths.Where(pair => pair.Value >= level))
{
File.AppendAllText(p.Key, LogLine);
}
}
public enum LogLevel
{
ERROR = 1,
WARNING = 2,
INFO = 3,
DEBUG = 4
}
}
}