1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.async;
18
19 import java.util.concurrent.ThreadFactory;
20 import java.util.concurrent.TimeUnit;
21
22 import org.apache.logging.log4j.Level;
23 import org.apache.logging.log4j.core.AbstractLifeCycle;
24 import org.apache.logging.log4j.core.LogEvent;
25 import org.apache.logging.log4j.core.impl.Log4jLogEvent;
26 import org.apache.logging.log4j.core.impl.LogEventFactory;
27 import org.apache.logging.log4j.core.impl.MutableLogEvent;
28 import org.apache.logging.log4j.core.impl.ReusableLogEventFactory;
29 import org.apache.logging.log4j.core.jmx.RingBufferAdmin;
30 import org.apache.logging.log4j.core.util.Log4jThreadFactory;
31 import org.apache.logging.log4j.core.util.Throwables;
32 import org.apache.logging.log4j.message.ReusableMessage;
33
34 import com.lmax.disruptor.EventFactory;
35 import com.lmax.disruptor.EventTranslatorTwoArg;
36 import com.lmax.disruptor.ExceptionHandler;
37 import com.lmax.disruptor.RingBuffer;
38 import com.lmax.disruptor.Sequence;
39 import com.lmax.disruptor.SequenceReportingEventHandler;
40 import com.lmax.disruptor.TimeoutException;
41 import com.lmax.disruptor.WaitStrategy;
42 import com.lmax.disruptor.dsl.Disruptor;
43 import com.lmax.disruptor.dsl.ProducerType;
44
45
46
47
48
49
50
51
52
53
54
55
56
57 public class AsyncLoggerConfigDisruptor extends AbstractLifeCycle implements AsyncLoggerConfigDelegate {
58
59 private static final int MAX_DRAIN_ATTEMPTS_BEFORE_SHUTDOWN = 200;
60 private static final int SLEEP_MILLIS_BETWEEN_DRAIN_ATTEMPTS = 50;
61
62
63
64
65 public static class Log4jEventWrapper {
66 public Log4jEventWrapper() {
67 }
68
69 public Log4jEventWrapper(final MutableLogEvent mutableLogEvent) {
70 event = mutableLogEvent;
71 }
72
73 private AsyncLoggerConfig loggerConfig;
74 private LogEvent event;
75
76
77
78
79 public void clear() {
80 loggerConfig = null;
81 if (event instanceof MutableLogEvent) {
82 ((MutableLogEvent) event).clear();
83 } else {
84 event = null;
85 }
86 }
87
88 @Override
89 public String toString() {
90 return String.valueOf(event);
91 }
92 }
93
94
95
96
97 private static class Log4jEventWrapperHandler implements SequenceReportingEventHandler<Log4jEventWrapper> {
98 private static final int NOTIFY_PROGRESS_THRESHOLD = 50;
99 private Sequence sequenceCallback;
100 private int counter;
101
102 @Override
103 public void setSequenceCallback(final Sequence sequenceCallback) {
104 this.sequenceCallback = sequenceCallback;
105 }
106
107 @Override
108 public void onEvent(final Log4jEventWrapper event, final long sequence, final boolean endOfBatch)
109 throws Exception {
110 event.event.setEndOfBatch(endOfBatch);
111 event.loggerConfig.asyncCallAppenders(event.event);
112 event.clear();
113
114 notifyIntermediateProgress(sequence);
115 }
116
117
118
119
120
121 private void notifyIntermediateProgress(final long sequence) {
122 if (++counter > NOTIFY_PROGRESS_THRESHOLD) {
123 sequenceCallback.set(sequence);
124 counter = 0;
125 }
126 }
127 }
128
129
130
131
132
133 private static final EventFactory<Log4jEventWrapper> FACTORY = new EventFactory<Log4jEventWrapper>() {
134 @Override
135 public Log4jEventWrapper newInstance() {
136 return new Log4jEventWrapper();
137 }
138 };
139
140
141
142
143
144 private static final EventFactory<Log4jEventWrapper> MUTABLE_FACTORY = new EventFactory<Log4jEventWrapper>() {
145 @Override
146 public Log4jEventWrapper newInstance() {
147 return new Log4jEventWrapper(new MutableLogEvent());
148 }
149 };
150
151
152
153
154 private static final EventTranslatorTwoArg<Log4jEventWrapper, LogEvent, AsyncLoggerConfig> TRANSLATOR =
155 new EventTranslatorTwoArg<Log4jEventWrapper, LogEvent, AsyncLoggerConfig>() {
156
157 @Override
158 public void translateTo(final Log4jEventWrapper ringBufferElement, final long sequence,
159 final LogEvent logEvent, final AsyncLoggerConfig loggerConfig) {
160 ringBufferElement.event = logEvent;
161 ringBufferElement.loggerConfig = loggerConfig;
162 }
163 };
164
165
166
167
168 private static final EventTranslatorTwoArg<Log4jEventWrapper, LogEvent, AsyncLoggerConfig> MUTABLE_TRANSLATOR =
169 new EventTranslatorTwoArg<Log4jEventWrapper, LogEvent, AsyncLoggerConfig>() {
170
171 @Override
172 public void translateTo(final Log4jEventWrapper ringBufferElement, final long sequence,
173 final LogEvent logEvent, final AsyncLoggerConfig loggerConfig) {
174 ((MutableLogEvent) ringBufferElement.event).initFrom(logEvent);
175 ringBufferElement.loggerConfig = loggerConfig;
176 }
177 };
178
179 private int ringBufferSize;
180 private AsyncQueueFullPolicy asyncQueueFullPolicy;
181 private Boolean mutable = Boolean.FALSE;
182
183 private volatile Disruptor<Log4jEventWrapper> disruptor;
184 private long backgroundThreadId;
185 private EventFactory<Log4jEventWrapper> factory;
186 private EventTranslatorTwoArg<Log4jEventWrapper, LogEvent, AsyncLoggerConfig> translator;
187 private volatile boolean alreadyLoggedWarning = false;
188
189 public AsyncLoggerConfigDisruptor() {
190 }
191
192
193 @Override
194 public void setLogEventFactory(final LogEventFactory logEventFactory) {
195
196
197 this.mutable = mutable || (logEventFactory instanceof ReusableLogEventFactory);
198 }
199
200
201
202
203
204
205
206 @Override
207 public synchronized void start() {
208 if (disruptor != null) {
209 LOGGER.trace("AsyncLoggerConfigDisruptor not starting new disruptor for this configuration, "
210 + "using existing object.");
211 return;
212 }
213 LOGGER.trace("AsyncLoggerConfigDisruptor creating new disruptor for this configuration.");
214 ringBufferSize = DisruptorUtil.calculateRingBufferSize("AsyncLoggerConfig.RingBufferSize");
215 final WaitStrategy waitStrategy = DisruptorUtil.createWaitStrategy("AsyncLoggerConfig.WaitStrategy");
216
217 final ThreadFactory threadFactory = new Log4jThreadFactory("AsyncLoggerConfig-", true, Thread.NORM_PRIORITY) {
218 @Override
219 public Thread newThread(final Runnable r) {
220 final Thread result = super.newThread(r);
221 backgroundThreadId = result.getId();
222 return result;
223 }
224 };
225 asyncQueueFullPolicy = AsyncQueueFullPolicyFactory.create();
226
227 translator = mutable ? MUTABLE_TRANSLATOR : TRANSLATOR;
228 factory = mutable ? MUTABLE_FACTORY : FACTORY;
229 disruptor = new Disruptor<>(factory, ringBufferSize, threadFactory, ProducerType.MULTI, waitStrategy);
230
231 final ExceptionHandler<Log4jEventWrapper> errorHandler = DisruptorUtil.getAsyncLoggerConfigExceptionHandler();
232 disruptor.setDefaultExceptionHandler(errorHandler);
233
234 final Log4jEventWrapperHandler[] handlers = {new Log4jEventWrapperHandler()};
235 disruptor.handleEventsWith(handlers);
236
237 LOGGER.debug("Starting AsyncLoggerConfig disruptor for this configuration with ringbufferSize={}, "
238 + "waitStrategy={}, exceptionHandler={}...", disruptor.getRingBuffer().getBufferSize(), waitStrategy
239 .getClass().getSimpleName(), errorHandler);
240 disruptor.start();
241 super.start();
242 }
243
244
245
246
247
248 @Override
249 public boolean stop(final long timeout, final TimeUnit timeUnit) {
250 final Disruptor<Log4jEventWrapper> temp = disruptor;
251 if (temp == null) {
252 LOGGER.trace("AsyncLoggerConfigDisruptor: disruptor for this configuration already shut down.");
253 return true;
254 }
255 setStopping();
256 LOGGER.trace("AsyncLoggerConfigDisruptor: shutting down disruptor for this configuration.");
257
258
259 disruptor = null;
260
261
262
263
264 for (int i = 0; hasBacklog(temp) && i < MAX_DRAIN_ATTEMPTS_BEFORE_SHUTDOWN; i++) {
265 try {
266 Thread.sleep(SLEEP_MILLIS_BETWEEN_DRAIN_ATTEMPTS);
267 } catch (final InterruptedException e) {
268 }
269 }
270 try {
271
272 temp.shutdown(timeout, timeUnit);
273 } catch (final TimeoutException e) {
274 LOGGER.warn("AsyncLoggerConfigDisruptor: shutdown timed out after {} {}", timeout, timeUnit);
275 temp.halt();
276 }
277 LOGGER.trace("AsyncLoggerConfigDisruptor: disruptor has been shut down.");
278
279 if (DiscardingAsyncQueueFullPolicy.getDiscardCount(asyncQueueFullPolicy) > 0) {
280 LOGGER.trace("AsyncLoggerConfigDisruptor: {} discarded {} events.", asyncQueueFullPolicy,
281 DiscardingAsyncQueueFullPolicy.getDiscardCount(asyncQueueFullPolicy));
282 }
283 setStopped();
284 return true;
285 }
286
287
288
289
290 private static boolean hasBacklog(final Disruptor<?> theDisruptor) {
291 final RingBuffer<?> ringBuffer = theDisruptor.getRingBuffer();
292 return !ringBuffer.hasAvailableCapacity(ringBuffer.getBufferSize());
293 }
294
295 @Override
296 public EventRoute getEventRoute(final Level logLevel) {
297 final int remainingCapacity = remainingDisruptorCapacity();
298 if (remainingCapacity < 0) {
299 return EventRoute.DISCARD;
300 }
301 return asyncQueueFullPolicy.getRoute(backgroundThreadId, logLevel);
302 }
303
304 private int remainingDisruptorCapacity() {
305 final Disruptor<Log4jEventWrapper> temp = disruptor;
306 if (hasLog4jBeenShutDown(temp)) {
307 return -1;
308 }
309 return (int) temp.getRingBuffer().remainingCapacity();
310 }
311
312
313
314
315 private boolean hasLog4jBeenShutDown(final Disruptor<Log4jEventWrapper> aDisruptor) {
316 if (aDisruptor == null) {
317 LOGGER.warn("Ignoring log event after log4j was shut down");
318 return true;
319 }
320 return false;
321 }
322
323 @Override
324 public void enqueueEvent(final LogEvent event, final AsyncLoggerConfig asyncLoggerConfig) {
325
326 try {
327 final LogEvent logEvent = prepareEvent(event);
328 enqueue(logEvent, asyncLoggerConfig);
329 } catch (final NullPointerException npe) {
330
331
332 LOGGER.warn("Ignoring log event after log4j was shut down: {} [{}] {}", event.getLevel(),
333 event.getLoggerName(), event.getMessage().getFormattedMessage()
334 + (event.getThrown() == null ? "" : Throwables.toStringList(event.getThrown())));
335 }
336 }
337
338 private LogEvent prepareEvent(final LogEvent event) {
339 LogEvent logEvent = ensureImmutable(event);
340 if (logEvent.getMessage() instanceof ReusableMessage) {
341 if (logEvent instanceof Log4jLogEvent) {
342 ((Log4jLogEvent) logEvent).makeMessageImmutable();
343 } else if (logEvent instanceof MutableLogEvent) {
344
345
346 if (translator != MUTABLE_TRANSLATOR) {
347
348 logEvent = ((MutableLogEvent) logEvent).createMemento();
349 }
350 } else {
351 showWarningAboutCustomLogEventWithReusableMessage(logEvent);
352 }
353 } else {
354 InternalAsyncUtil.makeMessageImmutable(logEvent.getMessage());
355 }
356 return logEvent;
357 }
358
359 private void showWarningAboutCustomLogEventWithReusableMessage(final LogEvent logEvent) {
360 if (!alreadyLoggedWarning) {
361 LOGGER.warn("Custom log event of type {} contains a mutable message of type {}." +
362 " AsyncLoggerConfig does not know how to make an immutable copy of this message." +
363 " This may result in ConcurrentModificationExceptions or incorrect log messages" +
364 " if the application modifies objects in the message while" +
365 " the background thread is writing it to the appenders.",
366 logEvent.getClass().getName(), logEvent.getMessage().getClass().getName());
367 alreadyLoggedWarning = true;
368 }
369 }
370
371 private void enqueue(final LogEvent logEvent, final AsyncLoggerConfig asyncLoggerConfig) {
372 disruptor.getRingBuffer().publishEvent(translator, logEvent, asyncLoggerConfig);
373 }
374
375 @Override
376 public boolean tryEnqueue(final LogEvent event, final AsyncLoggerConfig asyncLoggerConfig) {
377 final LogEvent logEvent = prepareEvent(event);
378 return disruptor.getRingBuffer().tryPublishEvent(translator, logEvent, asyncLoggerConfig);
379 }
380
381 private LogEvent ensureImmutable(final LogEvent event) {
382 LogEvent result = event;
383 if (event instanceof RingBufferLogEvent) {
384
385
386
387
388
389
390 result = ((RingBufferLogEvent) event).createMemento();
391 }
392 return result;
393 }
394
395
396
397
398
399
400
401 @Override
402 public RingBufferAdmin createRingBufferAdmin(final String contextName, final String loggerConfigName) {
403 return RingBufferAdmin.forAsyncLoggerConfig(disruptor.getRingBuffer(), contextName, loggerConfigName);
404 }
405 }