Skip to content
This repository was archived by the owner on Dec 13, 2018. It is now read-only.

Commit 4ba41aa

Browse files
committed
formatting logs for structured data
1 parent 47e6040 commit 4ba41aa

File tree

1 file changed

+73
-1
lines changed

1 file changed

+73
-1
lines changed

src/Microsoft.Framework.Logging.Console/ConsoleLogger.cs

Lines changed: 73 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,15 @@
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

44
using System;
5+
using System.Collections;
6+
using System.Globalization;
7+
using System.Text;
58

69
namespace Microsoft.Framework.Logging.Console
710
{
811
public class ConsoleLogger : ILogger
912
{
13+
private const int _indentation = 2;
1014
private readonly string _name;
1115
private Func<string, LogLevel, bool> _filter;
1216
private readonly object _lock = new object();
@@ -27,7 +31,17 @@ public void Write(LogLevel logLevel, int eventId, object state, Exception except
2731
return;
2832
}
2933
var message = string.Empty;
30-
if (formatter != null)
34+
if (state is ILoggerStructure)
35+
{
36+
var builder = new StringBuilder();
37+
FormatLoggerStructure(
38+
builder,
39+
(ILoggerStructure)state,
40+
level: 1,
41+
bullet: false);
42+
message = Convert.ToString(builder.ToString(), CultureInfo.InvariantCulture);
43+
}
44+
else if (formatter != null)
3145
{
3246
message = formatter(state, exception);
3347
}
@@ -98,5 +112,63 @@ public IDisposable BeginScope(object state)
98112
{
99113
return null;
100114
}
115+
116+
private void FormatLoggerStructure(StringBuilder builder, ILoggerStructure structure, int level, bool bullet)
117+
{
118+
var values = structure.GetValues();
119+
if (values == null)
120+
{
121+
return;
122+
}
123+
var isFirst = true;
124+
foreach (var kvp in values)
125+
{
126+
builder.AppendLine();
127+
if (bullet && isFirst)
128+
{
129+
builder.Append(' ', level * _indentation - 1)
130+
.Append('-');
131+
}
132+
else
133+
{
134+
builder.Append(' ', level * _indentation);
135+
}
136+
builder.Append(kvp.Key)
137+
.Append(": ");
138+
if (kvp.Value is IEnumerable && !(kvp.Value is string))
139+
{
140+
foreach (var value in (IEnumerable)kvp.Value)
141+
{
142+
if (value is ILoggerStructure)
143+
{
144+
FormatLoggerStructure(
145+
builder,
146+
(ILoggerStructure)value,
147+
level + 1,
148+
bullet: true);
149+
}
150+
else
151+
{
152+
builder.AppendLine()
153+
.Append(' ', (level + 1) * _indentation)
154+
.Append(value);
155+
}
156+
}
157+
}
158+
else if (kvp.Value is ILoggerStructure)
159+
{
160+
FormatLoggerStructure(
161+
builder,
162+
(ILoggerStructure)kvp.Value,
163+
level + 1,
164+
bullet: false);
165+
}
166+
else
167+
{
168+
builder.Append(kvp.Value);
169+
}
170+
isFirst = false;
171+
}
172+
}
101173
}
102174
}

0 commit comments

Comments
 (0)