-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSimpleLogger.cs
78 lines (63 loc) · 2.68 KB
/
SimpleLogger.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
using EleCho.ConsoleAnsi;
namespace MiraiGoC
{
/// <summary>
/// 基于虚拟终端 ANSI 转义序列的简单日志类
/// (Console.Background 和 Console.Foreground 在 Linux 上是不支持的, 为了兼容性, 使用 ANSI 转义序列)
/// </summary>
class SimpleLogger
{
readonly List<TextWriter> extraTargets = new List<TextWriter>();
public SimpleLogger() { }
public SimpleLogger WithTarget(TextWriter stream)
{
extraTargets.Add(stream);
return this;
}
public SimpleLogger RemoveTarget(TextWriter stream)
{
extraTargets.Remove(stream);
return this;
}
public SimpleLogger LogInfo(string info)
{
foreach (TextWriter target in extraTargets)
target.WriteLine($"[{DateTime.Now}][INFO] {info}");
Console.WriteLine($"[{DateTime.Now}][INFO] {info}"); // 不附加格式
return this;
}
public SimpleLogger LogWarning(string warning)
{
foreach (TextWriter target in extraTargets)
target.WriteLine($"[{DateTime.Now}][WARNING] {warning}");
Console.WriteLine(new ConsoleAnsiSeq()
.SetForeColor(ConsoleColor.Yellow) // 颜色
.AppendText($"[{DateTime.Now}][WARNING] {warning}") // 内容
.SetTextFormat(SgrCode.Default) // 重置格式
.Build());
return this;
}
public SimpleLogger LogError(string error)
{
foreach (TextWriter target in extraTargets)
target.WriteLine($"[{DateTime.Now}][ERROR] {error}");
Console.WriteLine(new ConsoleAnsiSeq()
.SetForeColor(ConsoleColor.Red ) // 颜色
.AppendText($"[{DateTime.Now}][ERROR] {error}") // 内容
.SetTextFormat(SgrCode.Default) // 重置格式
.Build());
return this;
}
public SimpleLogger LogDebug(string msg)
{
foreach (TextWriter target in extraTargets)
target.WriteLine($"[{DateTime.Now}][DEBUG] {msg}");
Console.WriteLine(new ConsoleAnsiSeq()
.SetForeColor(ConsoleColor.Green) // 颜色
.AppendText($"[{DateTime.Now}][DEBUG] {msg}") // 内容
.SetTextFormat(SgrCode.Default) // 重置格式
.Build());
return this;
}
}
}