1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.appender;
18
19 import java.io.Serializable;
20 import java.util.ArrayList;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.concurrent.ArrayBlockingQueue;
24 import java.util.concurrent.BlockingQueue;
25 import java.util.concurrent.atomic.AtomicLong;
26
27 import org.apache.logging.log4j.core.Appender;
28 import org.apache.logging.log4j.core.Filter;
29 import org.apache.logging.log4j.core.LogEvent;
30 import org.apache.logging.log4j.core.async.RingBufferLogEvent;
31 import org.apache.logging.log4j.core.config.AppenderControl;
32 import org.apache.logging.log4j.core.config.AppenderRef;
33 import org.apache.logging.log4j.core.config.Configuration;
34 import org.apache.logging.log4j.core.config.ConfigurationException;
35 import org.apache.logging.log4j.core.config.plugins.Plugin;
36 import org.apache.logging.log4j.core.config.plugins.PluginAliases;
37 import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
38 import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
39 import org.apache.logging.log4j.core.config.plugins.PluginElement;
40 import org.apache.logging.log4j.core.config.plugins.PluginFactory;
41 import org.apache.logging.log4j.core.impl.Log4jLogEvent;
42
43
44
45
46
47
48
49 @Plugin(name = "Async", category = "Core", elementType = "appender", printObject = true)
50 public final class AsyncAppender extends AbstractAppender {
51
52 private static final long serialVersionUID = 1L;
53 private static final int DEFAULT_QUEUE_SIZE = 128;
54 private static final String SHUTDOWN = "Shutdown";
55
56 private final BlockingQueue<Serializable> queue;
57 private final int queueSize;
58 private final boolean blocking;
59 private final Configuration config;
60 private final AppenderRef[] appenderRefs;
61 private final String errorRef;
62 private final boolean includeLocation;
63 private AppenderControl errorAppender;
64 private AsyncThread thread;
65 private static final AtomicLong threadSequence = new AtomicLong(1);
66 private static ThreadLocal<Boolean> isAppenderThread = new ThreadLocal<>();
67
68
69 private AsyncAppender(final String name, final Filter filter, final AppenderRef[] appenderRefs,
70 final String errorRef, final int queueSize, final boolean blocking,
71 final boolean ignoreExceptions, final Configuration config,
72 final boolean includeLocation) {
73 super(name, filter, null, ignoreExceptions);
74 this.queue = new ArrayBlockingQueue<>(queueSize);
75 this.queueSize = queueSize;
76 this.blocking = blocking;
77 this.config = config;
78 this.appenderRefs = appenderRefs;
79 this.errorRef = errorRef;
80 this.includeLocation = includeLocation;
81 }
82
83 @Override
84 public void start() {
85 final Map<String, Appender> map = config.getAppenders();
86 final List<AppenderControl> appenders = new ArrayList<>();
87 for (final AppenderRef appenderRef : appenderRefs) {
88 final Appender appender = map.get(appenderRef.getRef());
89 if (appender != null) {
90 appenders.add(new AppenderControl(appender, appenderRef.getLevel(), appenderRef.getFilter()));
91 } else {
92 LOGGER.error("No appender named {} was configured", appenderRef);
93 }
94 }
95 if (errorRef != null) {
96 final Appender appender = map.get(errorRef);
97 if (appender != null) {
98 errorAppender = new AppenderControl(appender, null, null);
99 } else {
100 LOGGER.error("Unable to set up error Appender. No appender named {} was configured", errorRef);
101 }
102 }
103 if (appenders.size() > 0) {
104 thread = new AsyncThread(appenders, queue);
105 thread.setName("AsyncAppender-" + getName());
106 } else if (errorRef == null) {
107 throw new ConfigurationException("No appenders are available for AsyncAppender " + getName());
108 }
109
110 thread.start();
111 super.start();
112 }
113
114 @Override
115 public void stop() {
116 super.stop();
117 LOGGER.trace("AsyncAppender stopping. Queue still has {} events.", queue.size());
118 thread.shutdown();
119 try {
120 thread.join();
121 } catch (final InterruptedException ex) {
122 LOGGER.warn("Interrupted while stopping AsyncAppender {}", getName());
123 }
124 LOGGER.trace("AsyncAppender stopped. Queue has {} events.", queue.size());
125 }
126
127
128
129
130
131
132
133 @Override
134 public void append(LogEvent logEvent) {
135 if (!isStarted()) {
136 throw new IllegalStateException("AsyncAppender " + getName() + " is not active");
137 }
138 if (!(logEvent instanceof Log4jLogEvent)) {
139 if (!(logEvent instanceof RingBufferLogEvent)) {
140 return;
141 }
142 logEvent = ((RingBufferLogEvent) logEvent).createMemento();
143 }
144 logEvent.getMessage().getFormattedMessage();
145 final Log4jLogEvent coreEvent = (Log4jLogEvent) logEvent;
146 boolean appendSuccessful = false;
147 if (blocking) {
148 if (isAppenderThread.get() == Boolean.TRUE && queue.remainingCapacity() == 0) {
149
150
151 coreEvent.setEndOfBatch(false);
152 appendSuccessful = thread.callAppenders(coreEvent);
153 } else {
154 final Serializable serialized = Log4jLogEvent.serialize(coreEvent, includeLocation);
155 try {
156
157 queue.put(serialized);
158 appendSuccessful = true;
159 } catch (final InterruptedException e) {
160
161
162
163
164
165
166
167
168
169
170
171 appendSuccessful = queue.offer(serialized);
172 if (!appendSuccessful) {
173 LOGGER.warn("Interrupted while waiting for a free slot in the AsyncAppender LogEvent-queue {}",
174 getName());
175 }
176
177 Thread.currentThread().interrupt();
178 }
179 }
180 } else {
181 appendSuccessful = queue.offer(Log4jLogEvent.serialize(coreEvent, includeLocation));
182 if (!appendSuccessful) {
183 error("Appender " + getName() + " is unable to write primary appenders. queue is full");
184 }
185 }
186 if (!appendSuccessful && errorAppender != null) {
187 errorAppender.callAppender(coreEvent);
188 }
189 }
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205 @PluginFactory
206 public static AsyncAppender createAppender(@PluginElement("AppenderRef") final AppenderRef[] appenderRefs,
207 @PluginAttribute("errorRef") @PluginAliases("error-ref") final String errorRef,
208 @PluginAttribute(value = "blocking", defaultBoolean = true) final boolean blocking,
209 @PluginAttribute(value = "bufferSize", defaultInt = DEFAULT_QUEUE_SIZE) final int size,
210 @PluginAttribute("name") final String name,
211 @PluginAttribute(value = "includeLocation", defaultBoolean = false) final boolean includeLocation,
212 @PluginElement("Filter") final Filter filter,
213 @PluginConfiguration final Configuration config,
214 @PluginAttribute(value = "ignoreExceptions", defaultBoolean = true) final boolean ignoreExceptions) {
215 if (name == null) {
216 LOGGER.error("No name provided for AsyncAppender");
217 return null;
218 }
219 if (appenderRefs == null) {
220 LOGGER.error("No appender references provided to AsyncAppender {}", name);
221 }
222
223 return new AsyncAppender(name, filter, appenderRefs, errorRef,
224 size, blocking, ignoreExceptions, config, includeLocation);
225 }
226
227
228
229
230 private class AsyncThread extends Thread {
231
232 private volatile boolean shutdown = false;
233 private final List<AppenderControl> appenders;
234 private final BlockingQueue<Serializable> queue;
235
236 public AsyncThread(final List<AppenderControl> appenders, final BlockingQueue<Serializable> queue) {
237 this.appenders = appenders;
238 this.queue = queue;
239 setDaemon(true);
240 setName("AsyncAppenderThread" + threadSequence.getAndIncrement());
241 }
242
243 @Override
244 public void run() {
245 isAppenderThread.set(Boolean.TRUE);
246 while (!shutdown) {
247 Serializable s;
248 try {
249 s = queue.take();
250 if (s != null && s instanceof String && SHUTDOWN.equals(s.toString())) {
251 shutdown = true;
252 continue;
253 }
254 } catch (final InterruptedException ex) {
255 break;
256 }
257 final Log4jLogEvent event = Log4jLogEvent.deserialize(s);
258 event.setEndOfBatch(queue.isEmpty());
259 final boolean success = callAppenders(event);
260 if (!success && errorAppender != null) {
261 try {
262 errorAppender.callAppender(event);
263 } catch (final Exception ex) {
264
265 }
266 }
267 }
268
269 LOGGER.trace("AsyncAppender.AsyncThread shutting down. Processing remaining {} queue events.",
270 queue.size());
271 int count= 0;
272 int ignored = 0;
273 while (!queue.isEmpty()) {
274 try {
275 final Serializable s = queue.take();
276 if (Log4jLogEvent.canDeserialize(s)) {
277 final Log4jLogEvent event = Log4jLogEvent.deserialize(s);
278 event.setEndOfBatch(queue.isEmpty());
279 callAppenders(event);
280 count++;
281 } else {
282 ignored++;
283 LOGGER.trace("Ignoring event of class {}", s.getClass().getName());
284 }
285 } catch (final InterruptedException ex) {
286
287
288 }
289 }
290 LOGGER.trace("AsyncAppender.AsyncThread stopped. Queue has {} events remaining. " +
291 "Processed {} and ignored {} events since shutdown started.",
292 queue.size(), count, ignored);
293 }
294
295
296
297
298
299
300
301
302
303
304 boolean callAppenders(final Log4jLogEvent event) {
305 boolean success = false;
306 for (final AppenderControl control : appenders) {
307 try {
308 control.callAppender(event);
309 success = true;
310 } catch (final Exception ex) {
311
312 }
313 }
314 return success;
315 }
316
317 public void shutdown() {
318 shutdown = true;
319 if (queue.isEmpty()) {
320 queue.offer(SHUTDOWN);
321 }
322 }
323 }
324
325
326
327
328
329
330 public String[] getAppenderRefStrings() {
331 final String[] result = new String[appenderRefs.length];
332 for (int i = 0; i < result.length; i++) {
333 result[i] = appenderRefs[i].getRef();
334 }
335 return result;
336 }
337
338
339
340
341
342
343
344 public boolean isIncludeLocation() {
345 return includeLocation;
346 }
347
348
349
350
351
352
353 public boolean isBlocking() {
354 return blocking;
355 }
356
357
358
359
360
361 public String getErrorRef() {
362 return errorRef;
363 }
364
365 public int getQueueCapacity() {
366 return queueSize;
367 }
368
369 public int getQueueRemainingCapacity() {
370 return queue.remainingCapacity();
371 }
372 }