/
JacksonJsonLayout.java
387 lines (315 loc) · 13.5 KB
/
JacksonJsonLayout.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
377
378
379
380
381
382
383
384
385
386
387
package org.appenders.log4j2.elasticsearch;
/*-
* #%L
* log4j2-elasticsearch
* %%
* Copyright (C) 2018 Rafal Foltynski
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.util.MinimalPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationException;
import org.apache.logging.log4j.core.layout.AbstractLayout;
import org.apache.logging.log4j.message.Message;
import org.appenders.log4j2.elasticsearch.json.jackson.ExtendedLog4j2JsonModule;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
/**
* Allows to customize serialization of incoming events. See {@link Builder} API docs for more details
*
* @deprecated As of 1.7, this class will be removed. Use {@link GenericItemSourceLayout}
* (or {@link JacksonJsonLayoutPlugin} for Log4j2 XML config support) instead.
*/
@Deprecated
public class JacksonJsonLayout extends AbstractLayout<ItemSource> implements LegacyItemSourceLayout, LifeCycle {
private volatile State state = State.STOPPED;
private final ObjectWriter objectWriter;
private final ItemSourceFactory itemSourceFactory;
protected JacksonJsonLayout(Configuration config, ObjectWriter configuredWriter, ItemSourceFactory itemSourceFactory) {
super(config, null, null);
this.objectWriter = configuredWriter;
this.itemSourceFactory = itemSourceFactory;
}
@Override
public String getContentType() {
return "application/json";
}
@Override
public byte[] toByteArray(LogEvent event) {
throw new UnsupportedOperationException("Cannot return unwrapped byte array. Use ItemSource based API");
}
@Override
public final ItemSource toSerializable(LogEvent event) {
return serialize(event);
}
@Override
public final ItemSource serialize(LogEvent event) {
return itemSourceFactory.create(event, objectWriter);
}
@Override
public final ItemSource serialize(Message message) {
return itemSourceFactory.create(message, objectWriter);
}
@Override
public final ItemSource serialize(Object source) {
return itemSourceFactory.create(source, objectWriter);
}
public static JacksonJsonLayout.Builder newBuilder() {
return new JacksonJsonLayout.Builder();
}
public static class Builder extends org.apache.logging.log4j.core.layout.AbstractLayout.Builder<JacksonJsonLayout.Builder> implements org.apache.logging.log4j.core.util.Builder<JacksonJsonLayout> {
/**
* Default: {@link StringItemSourceFactory}
*/
static final ItemSourceFactory DEFAULT_SOURCE_FACTORY = StringItemSourceFactory.newBuilder().build();
/**
* Default: {@code [ExtendedLog4j2JsonModule]}
*/
static final JacksonModule[] DEFAULT_JACKSON_MODULES = new JacksonModule[]{
new ExtendedLog4j2JsonModule()
};
private ItemSourceFactory itemSourceFactory = DEFAULT_SOURCE_FACTORY;
private JacksonMixIn[] mixins = new JacksonMixIn[0];
private JacksonModule[] jacksonModules = DEFAULT_JACKSON_MODULES;
private VirtualProperty[] virtualProperties = new VirtualProperty[0];
private VirtualPropertyFilter[] virtualPropertyFilters = new VirtualPropertyFilter[0];
private boolean useAfterburner;
private boolean singleThread;
@Override
public JacksonJsonLayout build() {
if (getConfiguration() == null) {
throw new ConfigurationException("No Configuration instance provided for " + JacksonJsonLayout.class.getSimpleName());
}
return new JacksonJsonLayout(
getConfiguration(),
createConfiguredWriter(),
itemSourceFactory
);
}
protected ObjectWriter createConfiguredWriter() {
ObjectMapper objectMapper = createDefaultObjectMapper();
return configureModules(objectMapper, getJacksonModules())
.configureMixins(objectMapper, Arrays.asList(mixins))
.configureVirtualProperties(objectMapper, virtualProperties, virtualPropertyFilters)
.createConfiguredWriter(objectMapper);
}
private Collection<JacksonModule> getJacksonModules() {
LinkedList<JacksonModule> linkedList = new LinkedList<>(Arrays.asList(DEFAULT_JACKSON_MODULES));
linkedList.addAll(Arrays.asList(this.jacksonModules));
if (useAfterburner) {
// com.fasterxml.jackson.module:jackson-module-afterburner required here
linkedList.add(new JacksonAfterburnerModuleConfigurer());
}
return new JacksonModulesList(linkedList);
}
protected ObjectWriter createConfiguredWriter(ObjectMapper objectMapper) {
return objectMapper.writer(new MinimalPrettyPrinter());
}
protected Builder configureModules(ObjectMapper objectMapper, Collection<JacksonModule> modules) {
for (JacksonModule module : modules) {
module.applyTo(objectMapper);
}
return this;
}
protected Builder configureMixins(ObjectMapper objectMapper, List<JacksonMixIn> mixins) {
for (JacksonMixIn mixin : mixins) {
objectMapper.addMixIn(mixin.getTargetClass(), mixin.getMixInClass());
}
return this;
}
protected Builder configureVirtualProperties(ObjectMapper objectMapper, VirtualProperty[] virtualProperties, VirtualPropertyFilter[] virtualPropertyFilters) {
ValueResolver valueResolver = createValueResolver();
for (VirtualProperty property : virtualProperties) {
if (!property.isDynamic()) {
property.setValue(valueResolver.resolve(property.getValue()));
}
}
SerializationConfig customConfig = objectMapper.getSerializationConfig()
.with(new JacksonHandlerInstantiator(
virtualProperties,
valueResolver,
virtualPropertyFilters
));
objectMapper.setConfig(customConfig);
return this;
}
/**
* @return resolver used when {@link VirtualProperty}(-ies) configured
*/
protected ValueResolver createValueResolver() {
return new Log4j2Lookup(getConfiguration().getStrSubstitutor());
}
protected ObjectMapper createDefaultObjectMapper() {
return new ExtendedObjectMapper(createJsonFactory())
.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
.configure(SerializationFeature.CLOSE_CLOSEABLE, false);
}
protected JsonFactory createJsonFactory() {
if (singleThread) {
return new SingleThreadJsonFactoryProvider().create();
}
return new JsonFactory();
}
/**
* @param itemSourceFactory {@link ItemSource} producer
* @return this
*/
public Builder withItemSourceFactory(ItemSourceFactory itemSourceFactory) {
this.itemSourceFactory = itemSourceFactory;
return this;
}
/**
* Allows to customize {@link LogEvent} and {@link Message} serialization,
* including user-provided {@link org.apache.logging.log4j.message.ObjectMessage}
*
* @param mixins mixins to be applied
* @return this
*/
public Builder withMixins(JacksonMixIn... mixins) {
this.mixins = mixins;
return this;
}
/**
* Allows to append properties to serialized {@link LogEvent} and {@link Message}.
*
* Non-dynamic properties ({@code VirtualProperty#dynamic == false}) will be resolved on {@link #build()} call.
*
* Dynamic properties ({@code VirtualProperty#isDynamic == true}) will NOT be resolved on {@link #build()} call and resolution will be deferred to underlying {@link VirtualPropertiesWriter}.
*
* Similar to Log4j2 {@code KeyValuePair}.
*
* @param virtualProperties properties to be appended to JSON output
* @return this
*/
public Builder withVirtualProperties(VirtualProperty... virtualProperties) {
this.virtualProperties = virtualProperties;
return this;
}
/**
* Allows to define inclusion/exclusion filters for {@link VirtualProperty}-ies.
*
* @param virtualPropertyFilters filters to be applied to each configured {@link VirtualProperty}
* @return this
*/
public Builder withVirtualPropertyFilters(VirtualPropertyFilter[] virtualPropertyFilters) {
this.virtualPropertyFilters = virtualPropertyFilters;
return this;
}
/**
* Allows to configure {@link AfterburnerModule} - (de)serialization optimizer
*
* @param useAfterburner if true, {@link AfterburnerModule} will be used, false otherwise
* @return this
*/
public Builder withAfterburner(boolean useAfterburner) {
this.useAfterburner = useAfterburner;
return this;
}
/**
* Allows to configure {@code org.appenders.st.jackson.SingleThreadJsonFactory}
*
* NOTE: Use ONLY when {@link JacksonJsonLayout#serialize(LogEvent)}/{@link JacksonJsonLayout#serialize(Message)}
* are called exclusively by a one thread at a time, e.g. with AsyncLogger
*
* @param singleThread if true, {@code org.appenders.st.jackson.SingleThreadJsonFactory} will be used to create serializers,
* otherwise {@code com.fasterxml.jackson.core.JsonFactory} will be used
* @return this
*/
public Builder withSingleThread(boolean singleThread) {
this.singleThread = singleThread;
return this;
}
/**
* Allow to configure additional {@code com.fasterxml.jackson.databind.Module} implementations
*
* @param modules Jackson modules to register on {@link #build()}
* @return this
*/
public Builder withJacksonModules(JacksonModule... modules) {
this.jacksonModules = modules;
return this;
}
/**
* First-comes, first-served {@link JacksonModule} linked list. Ensures that no more than one element of specific type is present.
*/
private static class JacksonModulesList extends LinkedHashSet<JacksonModule> {
public JacksonModulesList(LinkedList<JacksonModule> linkedList) {
super(linkedList);
}
/**
* Adds given {@link JacksonModule} to the list if element of the same type is not already present.
*
* @param jacksonModule {@link JacksonModule} to add
* @return <i>true</i>, if element was added, <i>false</i> otherwise
*/
@Override
public boolean add(JacksonModule jacksonModule) {
if (this.contains(jacksonModule)) {
return false;
}
return super.add(jacksonModule);
}
/**
* Checks if this list contains an element with the same class name.
*
* @param o element to check
* @return <i>true</i> if element is present, <i>false</i> otherwise
*/
@Override
public boolean contains(Object o) {
for (JacksonModule jacksonModule : this) {
if (jacksonModule.getClass().getName().equals(o.getClass().getName())) {
return true;
}
}
return false;
}
}
}
// ==========
// LIFECYCLE
// ==========
@Override
public void start() {
itemSourceFactory.start();
state = State.STARTED;
}
@Override
public void stop() {
if (!itemSourceFactory.isStopped()) {
itemSourceFactory.stop();
}
state = State.STOPPED;
}
@Override
public boolean isStarted() {
return state == State.STARTED;
}
@Override
public boolean isStopped() {
return state == State.STOPPED;
}
}