-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLogger.cs
106 lines (96 loc) · 2.82 KB
/
Logger.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System;
using System.Diagnostics;
using System.IO;
// TODO replace with an actual logger
namespace Quack
{
public enum LogLevel
{
Debug,
Info,
Warn,
Error
}
public class Logger
{
private const string LogFileName = "log.txt";
private readonly string outputDirectory;
private string LogPrefix { get; set; }
public Logger(string outputDirectory)
{
this.outputDirectory = outputDirectory;
Info("NEW RUN: logger started");
this.LogPrefix = "";
}
// TODO this is stupid and probably slow
private void setPrefixToCallerClass()
{
var methodInfo = new StackTrace().GetFrame(3)?.GetMethod();
LogPrefix = methodInfo?.ReflectedType?.Name ?? "";
}
public void Plain(LogLevel level, string message)
{
string logFilePath = Path.Combine(outputDirectory, LogFileName);
setPrefixToCallerClass();
// Only print info and higher to standard out
if (level >= LogLevel.Info)
{
Console.Write(message);
}
using (StreamWriter writer = File.AppendText(logFilePath))
{
writer.Write(message);
}
}
public void Log(LogLevel level, string message)
{
string logFilePath = Path.Combine(outputDirectory, LogFileName);
string logEntry;
if (LogPrefix != null)
{
logEntry = $"{DateTime.Now} [{level}][{LogPrefix}] {message}";
}
else
{
logEntry = $"{DateTime.Now} [{level}] {message}";
}
// Only print info and higher to standard out
if (level >= LogLevel.Info)
{
Console.WriteLine(logEntry);
}
using (StreamWriter writer = File.AppendText(logFilePath))
{
writer.WriteLine(logEntry);
}
}
public void Debug(string message)
{
setPrefixToCallerClass();
Log(LogLevel.Debug, message);
}
public void Info(string message)
{
setPrefixToCallerClass();
Log(LogLevel.Info, message);
}
public void Warn(string message)
{
setPrefixToCallerClass();
Log(LogLevel.Warn, message);
}
public void Error(string message)
{
setPrefixToCallerClass();
Log(LogLevel.Error, message);
}
public void Assert(bool condition, string message)
{
if (!condition)
{
Log(LogLevel.Error, message);
throw new Exception(message);
}
}
}
}