-
Notifications
You must be signed in to change notification settings - Fork 64
/
JSONEventLayout.java
376 lines (335 loc) · 9.22 KB
/
JSONEventLayout.java
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package com.cwbase.logback;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.ThrowableProxyUtil;
import ch.qos.logback.core.LayoutBase;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Adapt from XMLLayout
*
* @author kmtong
*
*/
public class JSONEventLayout extends LayoutBase<ILoggingEvent> {
private final int DEFAULT_SIZE = 256;
private final int UPPER_LIMIT = 2048;
private final static char DBL_QUOTE = '"';
private final static char COMMA = ',';
private StringBuilder buf = new StringBuilder(DEFAULT_SIZE);
private DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
private Pattern MDC_VAR_PATTERN = Pattern.compile("\\@\\{([^}^:-]*)(:-([^}]*)?)?\\}");
private boolean locationInfo = false;
private int callerStackIdx = 0;
private boolean properties = false;
String source;
String sourceHost;
String sourcePath;
List<String> tags;
List<AdditionalField> additionalFields;
String type;
public JSONEventLayout() {
try {
setSourceHost(InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException e) {
}
}
@Override
public void start() {
super.start();
}
/**
* The <b>LocationInfo</b> option takes a boolean value. By default, it is
* set to false which means there will be no location information output by
* this layout. If the the option is set to true, then the file name and
* line number of the statement at the origin of the log statement will be
* output.
*
* <p>
* If you are embedding this layout within an
* <code>org.apache.log4j.net.SMTPAppender</code> then make sure to set the
* <b>LocationInfo</b> option of that appender as well.
*/
public void setLocationInfo(boolean flag) {
locationInfo = flag;
}
/**
* Returns the current value of the <b>LocationInfo</b> option.
*/
public boolean getLocationInfo() {
return locationInfo;
}
/**
* Sets whether MDC key-value pairs should be output, default false.
*
* @param flag
* new value.
* @since 1.2.15
*/
public void setProperties(final boolean flag) {
properties = flag;
}
/**
* Gets whether MDC key-value pairs should be output.
*
* @return true if MDC key-value pairs are output.
* @since 1.2.15
*/
public boolean getProperties() {
return properties;
}
/**
* Formats a {@link ILoggingEvent} in conformity with the log4j.dtd.
*/
public synchronized String doLayout(ILoggingEvent event) {
// Reset working buffer. If the buffer is too large, then we need a new
// one in order to avoid the penalty of creating a large array.
if (buf.capacity() > UPPER_LIMIT) {
buf = new StringBuilder(DEFAULT_SIZE);
} else {
buf.setLength(0);
}
Map<String, String> mdc = event.getMDCPropertyMap();
buf.append("{");
appendKeyValue(buf, "source", source, mdc);
buf.append(COMMA);
appendKeyValue(buf, "host", sourceHost, mdc);
buf.append(COMMA);
appendKeyValue(buf, "path", sourcePath, mdc);
buf.append(COMMA);
appendKeyValue(buf, "type", type, mdc);
buf.append(COMMA);
appendKeyValue(buf, "tags", tags, mdc);
buf.append(COMMA);
appendKeyValue(buf, "message", event.getFormattedMessage(), null);
buf.append(COMMA);
appendKeyValue(buf, "@timestamp",
df.format(new Date(event.getTimeStamp())), null);
buf.append(COMMA);
// ---- fields ----
appendKeyValue(buf, "logger", event.getLoggerName(), null);
buf.append(COMMA);
appendKeyValue(buf, "level", event.getLevel().toString(), null);
buf.append(COMMA);
appendKeyValue(buf, "thread", event.getThreadName(), null);
IThrowableProxy tp = event.getThrowableProxy();
if (tp != null) {
buf.append(COMMA);
String throwable = ThrowableProxyUtil.asString(tp);
appendKeyValue(buf, "throwable", throwable, null);
}
if (locationInfo) {
StackTraceElement[] callerDataArray = event.getCallerData();
if (callerDataArray != null
&& callerDataArray.length > callerStackIdx) {
buf.append(COMMA);
buf.append("\"location\":{");
StackTraceElement immediateCallerData = callerDataArray[callerStackIdx];
appendKeyValue(buf, "class",
immediateCallerData.getClassName(), null);
buf.append(COMMA);
appendKeyValue(buf, "method",
immediateCallerData.getMethodName(), null);
buf.append(COMMA);
appendKeyValue(buf, "file", immediateCallerData.getFileName(),
null);
buf.append(COMMA);
appendKeyValue(buf, "line",
Integer.toString(immediateCallerData.getLineNumber()),
null);
buf.append("}");
}
}
/*
* <log4j:properties> <log4j:data name="name" value="value"/>
* </log4j:properties>
*/
if (properties) {
Map<String, String> propertyMap = event.getMDCPropertyMap();
if ((propertyMap != null) && (propertyMap.size() != 0)) {
Set<Entry<String, String>> entrySet = propertyMap.entrySet();
buf.append(COMMA);
buf.append("\"properties\":{");
Iterator<Entry<String, String>> i = entrySet.iterator();
while (i.hasNext()) {
Entry<String, String> entry = i.next();
appendKeyValue(buf, entry.getKey(), entry.getValue(), null);
if (i.hasNext()) {
buf.append(COMMA);
}
}
buf.append("}");
}
}
if(additionalFields != null) {
for(AdditionalField field : additionalFields) {
buf.append(COMMA);
appendKeyValue(buf, field.getKey(), field.getValue(), mdc);
}
}
buf.append("}");
return buf.toString();
}
private void appendKeyValue(StringBuilder buf, String key, String value,
Map<String, String> mdc) {
if (value != null) {
buf.append(DBL_QUOTE);
buf.append(escape(key));
buf.append(DBL_QUOTE);
buf.append(':');
buf.append(DBL_QUOTE);
buf.append(escape(mdcSubst(value, mdc)));
buf.append(DBL_QUOTE);
} else {
buf.append(DBL_QUOTE);
buf.append(escape(key));
buf.append(DBL_QUOTE);
buf.append(':');
buf.append("null");
}
}
private void appendKeyValue(StringBuilder buf, String key,
List<String> values, Map<String, String> mdc) {
buf.append(DBL_QUOTE);
buf.append(escape(key));
buf.append(DBL_QUOTE);
buf.append(':');
buf.append('[');
if (values != null) {
Iterator<String> i = values.iterator();
while (i.hasNext()) {
String v = i.next();
buf.append(DBL_QUOTE);
buf.append(escape(mdcSubst(v, mdc)));
buf.append(DBL_QUOTE);
if (i.hasNext()) {
buf.append(',');
}
}
}
buf.append(']');
}
private String mdcSubst(String v, Map<String, String> mdc) {
if (mdc != null && v != null && v.contains("@{")) {
Matcher m = MDC_VAR_PATTERN.matcher(v);
StringBuffer sb = new StringBuffer(v.length());
while (m.find()) {
String val = mdc.get(m.group(1));
if (val == null) {
// If a default value exists, use it
val = (m.group(3) != null) ? val = m.group(3) : m.group(1) + "_NOT_FOUND";
}
m.appendReplacement(sb, Matcher.quoteReplacement(val));
}
m.appendTail(sb);
return sb.toString();
}
return v;
}
private String escape(String s) {
if (s == null)
return null;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
case '/':
sb.append("\\/");
break;
default:
if (ch >= '\u0000' && ch <= '\u001F') {
String ss = Integer.toHexString(ch);
sb.append("\\u");
for (int k = 0; k < 4 - ss.length(); k++) {
sb.append('0');
}
sb.append(ss.toUpperCase());
} else {
sb.append(ch);
}
}
}// for
return sb.toString();
}
@Override
public String getContentType() {
return "application/json";
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getSourceHost() {
return sourceHost;
}
public void setSourceHost(String sourceHost) {
this.sourceHost = sourceHost;
}
public String getSourcePath() {
return sourcePath;
}
public void setSourcePath(String sourcePath) {
this.sourcePath = sourcePath;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getCallerStackIdx() {
return callerStackIdx;
}
/**
* Location information dump with respect to call stack level. Some
* framework (Play) wraps the original logging method, and dumping the
* location always log the file of the wrapper instead of the actual caller.
* For PlayFramework, I use 2.
*
* @param callerStackIdx
*/
public void setCallerStackIdx(int callerStackIdx) {
this.callerStackIdx = callerStackIdx;
}
public void addAdditionalField(AdditionalField p) {
if(additionalFields == null) {
additionalFields = new ArrayList<AdditionalField>();
}
additionalFields.add(p);
}
}