/
SimpleConsoleFormatter.cs
218 lines (193 loc) · 8.2 KB
/
SimpleConsoleFormatter.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
namespace Microsoft.Extensions.Logging.Console
{
internal sealed class SimpleConsoleFormatter : ConsoleFormatter, IDisposable
{
private const string LoglevelPadding = ": ";
private static readonly string _messagePadding = new string(' ', GetLogLevelString(LogLevel.Information).Length + LoglevelPadding.Length);
private static readonly string _newLineWithMessagePadding = Environment.NewLine + _messagePadding;
private IDisposable _optionsReloadToken;
public SimpleConsoleFormatter(IOptionsMonitor<SimpleConsoleFormatterOptions> options)
: base (ConsoleFormatterNames.Simple)
{
ReloadLoggerOptions(options.CurrentValue);
_optionsReloadToken = options.OnChange(ReloadLoggerOptions);
}
private void ReloadLoggerOptions(SimpleConsoleFormatterOptions options)
{
FormatterOptions = options;
}
public void Dispose()
{
_optionsReloadToken?.Dispose();
}
internal SimpleConsoleFormatterOptions FormatterOptions { get; set; }
public override void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider scopeProvider, TextWriter textWriter)
{
string message = logEntry.Formatter(logEntry.State, logEntry.Exception);
if (logEntry.Exception == null && message == null)
{
return;
}
LogLevel logLevel = logEntry.LogLevel;
ConsoleColors logLevelColors = GetLogLevelConsoleColors(logLevel);
string logLevelString = GetLogLevelString(logLevel);
string timestamp = null;
string timestampFormat = FormatterOptions.TimestampFormat;
if (timestampFormat != null)
{
DateTimeOffset dateTimeOffset = GetCurrentDateTime();
timestamp = dateTimeOffset.ToString(timestampFormat);
}
if (timestamp != null)
{
textWriter.Write(timestamp);
}
if (logLevelString != null)
{
textWriter.WriteColoredMessage(logLevelString, logLevelColors.Background, logLevelColors.Foreground);
}
CreateDefaultLogMessage(textWriter, logEntry, message, scopeProvider);
}
private void CreateDefaultLogMessage<TState>(TextWriter textWriter, in LogEntry<TState> logEntry, string message, IExternalScopeProvider scopeProvider)
{
bool singleLine = FormatterOptions.SingleLine;
int eventId = logEntry.EventId.Id;
Exception exception = logEntry.Exception;
// Example:
// info: ConsoleApp.Program[10]
// Request received
// category and event id
textWriter.Write(LoglevelPadding);
textWriter.Write(logEntry.Category);
textWriter.Write('[');
#if NETCOREAPP
Span<char> span = stackalloc char[10];
if (eventId.TryFormat(span, out int charsWritten))
textWriter.Write(span.Slice(0, charsWritten));
else
#endif
textWriter.Write(eventId.ToString());
textWriter.Write(']');
if (!singleLine)
{
textWriter.Write(Environment.NewLine);
}
// scope information
WriteScopeInformation(textWriter, scopeProvider, singleLine);
WriteMessage(textWriter, message, singleLine);
// Example:
// System.InvalidOperationException
// at Namespace.Class.Function() in File:line X
if (exception != null)
{
// exception message
WriteMessage(textWriter, exception.ToString(), singleLine);
}
if (singleLine)
{
textWriter.Write(Environment.NewLine);
}
}
private void WriteMessage(TextWriter textWriter, string message, bool singleLine)
{
if (!string.IsNullOrEmpty(message))
{
if (singleLine)
{
textWriter.Write(' ');
WriteReplacing(textWriter, Environment.NewLine, " ", message);
}
else
{
textWriter.Write(_messagePadding);
WriteReplacing(textWriter, Environment.NewLine, _newLineWithMessagePadding, message);
textWriter.Write(Environment.NewLine);
}
}
static void WriteReplacing(TextWriter writer, string oldValue, string newValue, string message)
{
string newMessage = message.Replace(oldValue, newValue);
writer.Write(newMessage);
}
}
private DateTimeOffset GetCurrentDateTime()
{
return FormatterOptions.UseUtcTimestamp ? DateTimeOffset.UtcNow : DateTimeOffset.Now;
}
private static string GetLogLevelString(LogLevel logLevel)
{
return logLevel switch
{
LogLevel.Trace => "trce",
LogLevel.Debug => "dbug",
LogLevel.Information => "info",
LogLevel.Warning => "warn",
LogLevel.Error => "fail",
LogLevel.Critical => "crit",
_ => throw new ArgumentOutOfRangeException(nameof(logLevel))
};
}
private ConsoleColors GetLogLevelConsoleColors(LogLevel logLevel)
{
bool disableColors = (FormatterOptions.ColorBehavior == LoggerColorBehavior.Disabled) ||
(FormatterOptions.ColorBehavior == LoggerColorBehavior.Default && System.Console.IsOutputRedirected);
if (disableColors)
{
return new ConsoleColors(null, null);
}
// We must explicitly set the background color if we are setting the foreground color,
// since just setting one can look bad on the users console.
return logLevel switch
{
LogLevel.Trace => new ConsoleColors(ConsoleColor.Gray, ConsoleColor.Black),
LogLevel.Debug => new ConsoleColors(ConsoleColor.Gray, ConsoleColor.Black),
LogLevel.Information => new ConsoleColors(ConsoleColor.DarkGreen, ConsoleColor.Black),
LogLevel.Warning => new ConsoleColors(ConsoleColor.Yellow, ConsoleColor.Black),
LogLevel.Error => new ConsoleColors(ConsoleColor.Black, ConsoleColor.DarkRed),
LogLevel.Critical => new ConsoleColors(ConsoleColor.White, ConsoleColor.DarkRed),
_ => new ConsoleColors(null, null)
};
}
private void WriteScopeInformation(TextWriter textWriter, IExternalScopeProvider scopeProvider, bool singleLine)
{
if (FormatterOptions.IncludeScopes && scopeProvider != null)
{
bool paddingNeeded = !singleLine;
scopeProvider.ForEachScope((scope, state) =>
{
if (paddingNeeded)
{
paddingNeeded = false;
state.Write(_messagePadding);
state.Write("=> ");
}
else
{
state.Write(" => ");
}
state.Write(scope);
}, textWriter);
if (!paddingNeeded && !singleLine)
{
textWriter.Write(Environment.NewLine);
}
}
}
private readonly struct ConsoleColors
{
public ConsoleColors(ConsoleColor? foreground, ConsoleColor? background)
{
Foreground = foreground;
Background = background;
}
public ConsoleColor? Foreground { get; }
public ConsoleColor? Background { get; }
}
}
}