/
DefaultFormatter.cs
132 lines (106 loc) · 3.34 KB
/
DefaultFormatter.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
using System;
using System.Text;
using JetBrains.Annotations;
namespace Intersect.Logging.Formatting
{
public class DefaultFormatter : ILogFormatter
{
public const string DefaultTimestampFormat = "yyyy-MM-dd HH:mm:ss.fff";
public DefaultFormatter()
{
TimestampFormat = DefaultTimestampFormat;
}
[CanBeNull]
public string TimestampFormat { get; set; }
/// <inheritdoc />
public string Format(
LogConfiguration configuration,
LogLevel logLevel,
DateTime dateTime,
Exception exception,
string message,
params object[] args
)
{
var prefix = FormatPrefix(configuration, logLevel, dateTime);
var builder = new StringBuilder();
if (message != null)
{
FormatLine(builder, prefix, message, args);
}
if (exception != null)
{
FormatLine(builder, prefix, exception);
}
return builder.ToString();
}
[NotNull]
private string FormatPrefix([NotNull] LogConfiguration configuration, LogLevel logLevel, DateTime dateTime)
{
var builder = new StringBuilder();
if (!configuration.Pretty)
{
if (!string.IsNullOrWhiteSpace(TimestampFormat))
{
builder.Append(dateTime.ToString(TimestampFormat));
builder.Append(' ');
}
builder.Append($"[{logLevel}]");
builder.Append(' ');
}
// ReSharper disable once InvertIf
if (!string.IsNullOrEmpty(configuration.Tag))
{
builder.Append(configuration.Tag);
builder.Append(": ");
}
return builder.ToString();
}
private static void FormatLine(
[NotNull] StringBuilder builder,
[NotNull] string prefix,
[NotNull] string message,
params object[] args
)
{
builder.Append(prefix);
if (args?.Length > 0)
{
builder.AppendFormat(message, args);
}
else
{
builder.Append(message);
}
builder.AppendLine();
}
private static void FormatLine(
[NotNull] StringBuilder builder,
[CanBeNull] string prefix,
[NotNull] Exception exception,
bool recurse = true
)
{
if (!string.IsNullOrWhiteSpace(prefix))
{
builder.AppendLine(prefix);
}
builder.AppendLine($@" Message: {exception.Message}");
if (exception.StackTrace?.Length < 10000)
{
builder.AppendLine($@" Stack: {exception.StackTrace}");
}
builder.AppendLine();
if (!recurse)
{
return;
}
var innerException = exception;
while ((innerException = innerException.InnerException) != null)
{
builder.AppendLine(@"Caused By");
FormatLine(builder, null, innerException, false);
}
}
}
}