This repository has been archived by the owner on Dec 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 153
/
ColoredConsoleLogProvider.cs
67 lines (62 loc) · 2.33 KB
/
ColoredConsoleLogProvider.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
namespace LibLog.Example.ColoredConsoleLogProvider
{
using System;
using System.Collections.Generic;
using System.Globalization;
using LibLog.Example.Library.Logging;
using LibLog.Example.Library.Logging.LogProviders;
public class ColoredConsoleLogProvider : LogProviderBase
{
private static readonly Dictionary<LogLevel, ConsoleColor> Colors = new Dictionary<LogLevel, ConsoleColor>
{
{LogLevel.Fatal, ConsoleColor.Red},
{LogLevel.Error, ConsoleColor.Yellow},
{LogLevel.Warn, ConsoleColor.Magenta},
{LogLevel.Info, ConsoleColor.White},
{LogLevel.Debug, ConsoleColor.Gray},
{LogLevel.Trace, ConsoleColor.DarkGray},
};
public override Logger GetLogger(string name)
{
return (logLevel, messageFunc, exception, formatParameters) =>
{
if (messageFunc == null)
{
return true; // All log levels are enabled
}
if (Colors.TryGetValue(logLevel, out ConsoleColor consoleColor))
{
var originalForeground = Console.ForegroundColor;
try
{
Console.ForegroundColor = consoleColor;
WriteMessage(logLevel, name, messageFunc, formatParameters, exception);
}
finally
{
Console.ForegroundColor = originalForeground;
}
}
else
{
WriteMessage(logLevel, name, messageFunc, formatParameters, exception);
}
return true;
};
}
private static void WriteMessage(
LogLevel logLevel,
string name,
Func<string> messageFunc,
object[] formatParameters,
Exception exception)
{
var message = string.Format(CultureInfo.InvariantCulture, messageFunc(), formatParameters);
if (exception != null)
{
message = message + "|" + exception;
}
Console.WriteLine("{0} | {1} | {2} | {3}", DateTime.UtcNow, logLevel, name, message);
}
}
}