-
Notifications
You must be signed in to change notification settings - Fork 1
/
JsonMessageReader.cs
339 lines (298 loc) · 10.2 KB
/
JsonMessageReader.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This file is part of the Griffin+ common library suite (https://github.com/griffinplus/dotnet-libs-logging)
// The source code is licensed under the MIT license.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Globalization;
namespace GriffinPlus.Lib.Logging;
/// <summary>
/// Reads a log message written by <see cref="JsonMessageFormatter"/> returning <see cref="LogMessage"/>.
/// </summary>
public class JsonMessageReader
{
private enum State
{
Start,
ReadingObjectKey,
ExpectingColon,
ExpectingCommaOrEndOfObject,
ReadingTimestampValue,
ReadingHighPrecisionTimestampValue,
ReadingLogWriterValue,
ReadingLogLevelValue,
ReadingTagsValue,
ReadingTagsValueFirstElement,
ReadingTagsValueSubsequentElement,
ReadingTagsValueElementDelimiter,
ReadingApplicationNameValue,
ReadingProcessNameValue,
ReadingProcessIdValue,
ReadingTextValue
}
private readonly JsonTokenizer mTokenizer = new();
private readonly Stack<State> mStateStack = new();
private State mState = State.Start;
private State mReadingValueState;
private readonly List<ILogMessage> mCompletedLogMessages = [];
private LogMessage mLogMessage;
private readonly JsonMessageFieldNames mFieldNames;
/// <summary>
/// Initializes a new instance of the <see cref="JsonMessageReader"/> class.
/// </summary>
public JsonMessageReader()
{
mFieldNames = new JsonMessageFieldNames();
}
/// <summary>
/// Gets the field names defining how to map JSON keys to fields in <see cref="ILogMessage"/>.
/// </summary>
// ReSharper disable once ConvertToAutoPropertyWhenPossible
public JsonMessageFieldNames FieldNames => mFieldNames;
/// <summary>
/// Gets or sets the format of the timestamp.
/// </summary>
public string TimestampFormat { get; set; } = "u";
/// <summary>
/// Processes the specified JSON string and returns the corresponding log messages
/// (the passed data may contain incomplete JSON documents that are completed over multiple calls).
/// </summary>
/// <param name="data">JSON string to process.</param>
/// <returns>The log messages read from the JSON stream.</returns>
/// <exception cref="JsonMessageReaderException">Reading the log message failed due to a tokenization, parsing or format error.</exception>
public ILogMessage[] Process(string data)
{
mCompletedLogMessages.Clear();
int remainingTokenCount;
try
{
remainingTokenCount = mTokenizer.Process(data, false);
}
catch (TokenizingException ex)
{
// transform exception to ease the interface
throw new JsonMessageReaderException(
ex.LineNumber,
ex.Position,
ex.Message,
ex);
}
while (remainingTokenCount-- > 0)
{
JsonToken token = mTokenizer.Tokens.Dequeue();
switch (mState)
{
case State.Start:
{
if (token.Type != JsonTokenType.LBracket) ThrowUnexpectedTokenException(ref token);
mStateStack.Push(mState);
mState = State.ReadingObjectKey;
mLogMessage = new LogMessage();
break;
}
case State.ReadingObjectKey:
{
if (token.Type == JsonTokenType.RBracket)
{
// end of object
mState = mStateStack.Pop();
if (mState == State.Start) mCompletedLogMessages.Add(mLogMessage);
break;
}
if (token.Type == JsonTokenType.String)
{
// a JSON key
if (token.Token == mFieldNames.Timestamp) mReadingValueState = State.ReadingTimestampValue;
else if (token.Token == mFieldNames.HighPrecisionTimestamp) mReadingValueState = State.ReadingHighPrecisionTimestampValue;
else if (token.Token == mFieldNames.LogWriter) mReadingValueState = State.ReadingLogWriterValue;
else if (token.Token == mFieldNames.LogLevel) mReadingValueState = State.ReadingLogLevelValue;
else if (token.Token == mFieldNames.Tags) mReadingValueState = State.ReadingTagsValue;
else if (token.Token == mFieldNames.ApplicationName) mReadingValueState = State.ReadingApplicationNameValue;
else if (token.Token == mFieldNames.ProcessName) mReadingValueState = State.ReadingProcessNameValue;
else if (token.Token == mFieldNames.ProcessId) mReadingValueState = State.ReadingProcessIdValue;
else if (token.Token == mFieldNames.Text) mReadingValueState = State.ReadingTextValue;
else
{
throw new JsonMessageReaderException(
token.LineNumber,
token.Position,
$"'{token.Token}' at ({token.LineNumber},{token.Position}) is not a valid field name.");
}
mState = State.ExpectingColon;
break;
}
ThrowUnexpectedTokenException(ref token);
break;
}
case State.ExpectingColon:
{
if (token.Type != JsonTokenType.Colon) ThrowUnexpectedTokenException(ref token);
mState = mReadingValueState;
break;
}
case State.ExpectingCommaOrEndOfObject:
{
if (token.Type == JsonTokenType.Comma)
{
mState = State.ReadingObjectKey;
break;
}
if (token.Type == JsonTokenType.RBracket)
{
mState = mStateStack.Pop();
if (mState == State.Start) mCompletedLogMessages.Add(mLogMessage);
break;
}
ThrowUnexpectedTokenException(ref token);
break;
}
case State.ReadingTimestampValue:
{
if (token.Type != JsonTokenType.String) ThrowUnexpectedTokenException(ref token);
if (!DateTimeOffset.TryParseExact(token.Token, TimestampFormat, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out DateTimeOffset timestamp))
throw new JsonMessageReaderException(token.LineNumber, token.Position, $"The timestamp ({token.Token}) does not have the expected format.");
mLogMessage.Timestamp = timestamp;
mState = State.ExpectingCommaOrEndOfObject;
break;
}
case State.ReadingHighPrecisionTimestampValue:
{
if (token.Type != JsonTokenType.Number) ThrowUnexpectedTokenException(ref token);
if (!long.TryParse(token.Token, out long timestamp))
{
throw new JsonMessageReaderException(
token.LineNumber,
token.Position,
$"The high precision timestamp ({token.Token}) does not have the expected format.");
}
mLogMessage.HighPrecisionTimestamp = timestamp;
mState = State.ExpectingCommaOrEndOfObject;
break;
}
case State.ReadingLogWriterValue:
{
if (token.Type != JsonTokenType.String) ThrowUnexpectedTokenException(ref token);
mLogMessage.LogWriterName = token.Token;
mState = State.ExpectingCommaOrEndOfObject;
break;
}
case State.ReadingLogLevelValue:
{
if (token.Type != JsonTokenType.String) ThrowUnexpectedTokenException(ref token);
mLogMessage.LogLevelName = token.Token;
mState = State.ExpectingCommaOrEndOfObject;
break;
}
case State.ReadingTagsValue:
{
if (token.Type != JsonTokenType.LSquareBracket) ThrowUnexpectedTokenException(ref token);
mLogMessage.Tags = new TagSet();
mState = State.ReadingTagsValueFirstElement;
break;
}
case State.ReadingTagsValueFirstElement:
{
if (token.Type == JsonTokenType.RSquareBracket)
{
// end of tags array
mState = State.ExpectingCommaOrEndOfObject;
break;
}
if (token.Type == JsonTokenType.String)
{
// a tag
mLogMessage.Tags += token.Token;
mState = State.ReadingTagsValueElementDelimiter;
break;
}
ThrowUnexpectedTokenException(ref token);
break;
}
case State.ReadingTagsValueElementDelimiter:
{
if (token.Type == JsonTokenType.RSquareBracket)
{
// end of tags array
mState = State.ExpectingCommaOrEndOfObject;
break;
}
if (token.Type == JsonTokenType.Comma)
{
mState = State.ReadingTagsValueSubsequentElement;
break;
}
ThrowUnexpectedTokenException(ref token);
break;
}
case State.ReadingTagsValueSubsequentElement:
{
if (token.Type == JsonTokenType.String)
{
// a tag
mLogMessage.Tags += token.Token;
mState = State.ReadingTagsValueElementDelimiter;
break;
}
ThrowUnexpectedTokenException(ref token);
break;
}
case State.ReadingApplicationNameValue:
{
if (token.Type != JsonTokenType.String) ThrowUnexpectedTokenException(ref token);
mLogMessage.ApplicationName = token.Token;
mState = State.ExpectingCommaOrEndOfObject;
break;
}
case State.ReadingProcessNameValue:
{
if (token.Type != JsonTokenType.String) ThrowUnexpectedTokenException(ref token);
mLogMessage.ProcessName = token.Token;
mState = State.ExpectingCommaOrEndOfObject;
break;
}
case State.ReadingProcessIdValue:
{
if (token.Type != JsonTokenType.Number) ThrowUnexpectedTokenException(ref token);
if (!int.TryParse(token.Token, out int id))
throw new JsonMessageReaderException(token.LineNumber, token.Position, $"The process id ({token.Token}) does not have the expected format.");
mLogMessage.ProcessId = id;
mState = State.ExpectingCommaOrEndOfObject;
break;
}
case State.ReadingTextValue:
{
if (token.Type != JsonTokenType.String) ThrowUnexpectedTokenException(ref token);
mLogMessage.Text = token.Token;
mState = State.ExpectingCommaOrEndOfObject;
break;
}
default:
throw new NotImplementedException();
}
}
return mCompletedLogMessages.ToArray();
}
/// <summary>
/// Resets the reader.
/// </summary>
public void Reset()
{
mTokenizer.Reset();
mStateStack.Clear();
mState = State.Start;
mReadingValueState = State.Start;
mCompletedLogMessages.Clear();
mLogMessage = null;
}
/// <summary>
/// Throws a <see cref="JsonMessageReaderException"/> indicating that an unexpected token was found.
/// </summary>
/// <param name="token">The unexpected token.</param>
private static void ThrowUnexpectedTokenException(ref JsonToken token)
{
throw new JsonMessageReaderException(
token.LineNumber,
token.Position,
$"Unexpected token '{token.Token}' at ({token.LineNumber},{token.Position}).");
}
}