-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLogger.cs
More file actions
66 lines (57 loc) · 2.53 KB
/
Logger.cs
File metadata and controls
66 lines (57 loc) · 2.53 KB
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
using System;
using Microsoft.Extensions.Logging;
namespace krrTools
{
public static class Logger
{
private static ILogger? logger;
private static bool consoleOutputEnabled = true;
public static void Initialize(ILogger? logger)
{
Logger.logger = logger;
}
/// <summary>
/// 启用或禁用控制台输出。在单元测试中可以禁用以减少日志噪音。
/// </summary>
public static void SetConsoleOutputEnabled(bool enabled)
{
consoleOutputEnabled = enabled;
}
/// <code>Logger.WriteLine(LogLevel.Information, "xxxx{0}, {1}", a, b);</code>
/// <param name="level">日志等级</param>
/// <param name="message">信息</param>
/// <param name="args">lamda变量字段</param>
public static void WriteLine(LogLevel level, string message, params object[] args)
{
logger?.Log(level, message, args);
if (!consoleOutputEnabled)
return;
#if !DEBUG
if (level == LogLevel.Debug)
return; // Debug 级别日志在非调试模式下不输出到控制台
#endif
ConsoleColor color = level switch
{
LogLevel.Debug => ConsoleColor.Magenta,
LogLevel.Information => ConsoleColor.Green,
LogLevel.Warning => ConsoleColor.Yellow,
LogLevel.Error => ConsoleColor.Red,
LogLevel.Critical => ConsoleColor.Gray,
_ => ConsoleColor.Gray
};
string formatted = args.Length > 0 ? string.Format(message, args) : message;
string levelString = level switch
{
LogLevel.Debug => "Debug",
LogLevel.Information => "Info",
LogLevel.Warning => "Warning",
LogLevel.Error => "Error",
LogLevel.Critical => "Critical",
_ => "unknow"
};
Console.ForegroundColor = color;
Console.WriteLine($"{levelString}: {formatted}");
Console.ResetColor();
}
}
}