This repository has been archived by the owner on Apr 23, 2024. It is now read-only.
/
LogglyBatchAppender.java
426 lines (367 loc) · 14.6 KB
/
LogglyBatchAppender.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
/*
* Copyright 2012-2013 Ceki Gulcu, Les Hazlewood, et. al.
*
* 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.
*/
package ch.qos.logback.ext.loggly;
import ch.qos.logback.ext.loggly.io.DiscardingRollingOutputStream;
import ch.qos.logback.ext.loggly.io.IoUtils;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.sql.Timestamp;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
* <p>
* <a href="http://logback.qos.ch/">Logback</a> batch appender for <a href="http://www.loggly.com/">Loggly</a> HTTP API</a>.
* </p>
* <p><strong>Note:</strong>Loggly's Syslog API is much more scalable than the HTTP API which should mostly be used in
* low-volume or non-production systems. The HTTP API can be very convenient to workaround firewalls.</p>
* <p>If the {@link LogglyBatchAppender} saturates and discards log messages, the following warning message is
* appended to both Loggly and {@link System#err}: <br/>
* "<code>$date - OutputStream is full, discard previous logs</code>"</p>
* <h2>Configuration settings</h2>
* <table>
* <tr>
* <th>Property Name</th>
* <th>Type</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>inputKey</td>
* <td>String</td>
* <td>Loggly input key. "<code>inputKey</code>" or <code>endpointUrl</code> is required. Sample
* "<code>12345678-90ab-cdef-1234-567890abcdef</code>"</td>
* </tr>
* <tr>
* <td>endpointUrl</td>
* <td>String</td>
* <td>Loggly HTTP API endpoint URL. "<code>inputKey</code>" or <code>endpointUrl</code> is required. Sample:
* "<code>https://logs.loggly.com/inputs/12345678-90ab-cdef-1234-567890abcdef</code>"</td>
* </tr>
* <tr>
* <td>pattern</td>
* <td>String</td>
* <td>Pattern used for Loggly log messages. Default value is:
* <code>%d{"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",UTC} %-5level [%thread] %logger: %m%n</code>.</td>
* </tr>
* <tr>
* <td>proxyHost</td>
* <td>String</td>
* <td>hostname of a proxy server. If blank, no proxy is used (See {@link URL#openConnection(java.net.Proxy)}.</td>
* </tr>
* <tr>
* <td>proxyPort</td>
* <td>int</td>
* <td>port of a proxy server. Must be a valid int but is ignored if <code>proxyHost</code> is blank or null.</td>
* </tr>
* <tr>
* <td>jmxMonitoring</td>
* <td>boolean</td>
* <td>Enable registration of a monitoring MBean named
* "<code>ch.qos.logback:type=LogglyBatchAppender,name=LogglyBatchAppender@#hashcode#</code>". Default: <code>true</code>.</td>
* </tr>
* <tr>
* <td>maxNumberOfBuckets</td>
* <td>int</td>
* <td>Max number of buckets of in the byte buffer. Default value: <code>8</code>.</td>
* </tr>
* <tr>
* <td>maxBucketSizeInKilobytes</td>
* <td>int</td>
* <td>Max size of each bucket. Default value: <code>1024</code> Kilobytes (1MB).</td>
* </tr>
* <tr>
* <td>flushIntervalInSeconds</td>
* <td>int</td>
* <td>Interval of the buffer flush to Loggly API. Default value: <code>3</code>.</td>
* </tr>
* </table>
* Default configuration consumes up to 8 buffers of 1024 Kilobytes (1MB) each, which seems very reasonable even for small JVMs.
* If logs are discarded, try first to shorten the <code>flushIntervalInSeconds</code> parameter to "2s" or event "1s".
* <p/>
* <h2>Configuration Sample</h2>
* <pre><code>
* <configuration scan="true" scanPeriod="30 seconds" debug="true">
* <if condition='isDefined("logback.loggly.inputKey")'>
* <then>
* <appender name="loggly" class="ch.qos.logback.ext.loggly.LogglyBatchAppender">
* <inputKey>${logback.loggly.inputKey}</inputKey>
* <pattern>%d{yyyy/MM/dd HH:mm:ss,SSS} [${HOSTNAME}] [%thread] %-5level %logger{36} - %m %throwable{5}%n</pattern>
* <proxyHost>${logback.loggly.proxy.host:-}</proxyHost>
* <proxyPort>${logback.loggly.proxy.port:-8080}</proxyPort>
* <debug>${logback.loggly.debug:-false}</debug>
* </appender>
* <root level="WARN">
* <appender-ref ref="loggly"/>
* </root>
* </then>
* </if>
* </configuration>
* </code></pre>
* </p>
* <p/>
* <h2>Implementation decisions</h2>
* <ul>
* <li>Why buffer the generated log messages as bytes instead of using the
* {@link ch.qos.logback.core.read.CyclicBufferAppender} and buffering the {@link ch.qos.logback.classic.spi.ILoggingEvent} ?
* Because it is much easier to control the size in memory</li>
* <li>
* Why buffer in a byte array instead of directly writing in a {@link BufferedOutputStream} on the {@link HttpURLConnection} ?
* Because the Loggly API may not like such kind of streaming approach.
* </li>
* </ul>
*
* @author <a href="mailto:cleclerc@xebia.fr">Cyrille Le Clerc</a>
*/
public class LogglyBatchAppender<E> extends AbstractLogglyAppender<E> implements LogglyBatchAppenderMBean {
private boolean debug = false;
private int flushIntervalInSeconds = 3;
private DiscardingRollingOutputStream outputStream;
protected final AtomicLong sendDurationInNanos = new AtomicLong();
protected final AtomicLong sentBytes = new AtomicLong();
protected final AtomicInteger sendSuccessCount = new AtomicInteger();
protected final AtomicInteger sendExceptionCount = new AtomicInteger();
private ScheduledExecutorService scheduledExecutor;
private boolean jmxMonitoring = true;
private MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
private ObjectName registeredObjectName;
private int maxNumberOfBuckets = 8;
private int maxBucketSizeInKilobytes = 1024;
private Charset charset = Charset.forName("UTF-8");
@Override
protected void append(E eventObject) {
if (!isStarted()) {
return;
}
String msg = this.layout.doLayout(eventObject);
try {
outputStream.write(msg.getBytes(charset));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void start() {
// OUTPUTSTREAM
outputStream = new DiscardingRollingOutputStream(
maxBucketSizeInKilobytes * 1024,
maxNumberOfBuckets) {
@Override
protected void onBucketDiscard(ByteArrayOutputStream discardedBucket) {
if (isDebug()) {
addInfo("Discard bucket - " + getDebugInfo());
}
String s = new Timestamp(System.currentTimeMillis()) + " - OutputStream is full, discard previous logs" + LINE_SEPARATOR;
try {
getFilledBuckets().peekLast().write(s.getBytes());
addWarn(s);
} catch (IOException e) {
addWarn("Exception appending warning message '" + s + "'", e);
}
}
@Override
protected void onBucketRoll(ByteArrayOutputStream rolledBucket) {
if (isDebug()) {
addInfo("Roll bucket - " + getDebugInfo());
}
}
};
// SCHEDULER
ThreadFactory threadFactory = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = Executors.defaultThreadFactory().newThread(r);
thread.setName("logback-loggly-appender");
thread.setDaemon(true);
return thread;
}
};
scheduledExecutor = Executors.newSingleThreadScheduledExecutor(threadFactory);
scheduledExecutor.scheduleWithFixedDelay(new LogglyExporter(), flushIntervalInSeconds, flushIntervalInSeconds, TimeUnit.SECONDS);
// MONITORING
if (jmxMonitoring) {
String objectName = "ch.qos.logback:type=LogglyBatchAppender,name=LogglyBatchAppender@" + System.identityHashCode(this);
try {
registeredObjectName = mbeanServer.registerMBean(this, new ObjectName(objectName)).getObjectName();
} catch (Exception e) {
addWarn("Exception registering mbean '" + objectName + "'", e);
}
}
// super.setOutputStream() must be defined before calling super.start()
super.start();
}
@Override
public void stop() {
scheduledExecutor.shutdown();
processLogEntries();
if (registeredObjectName != null) {
try {
mbeanServer.unregisterMBean(registeredObjectName);
} catch (Exception e) {
addWarn("Exception unRegistering mbean " + registeredObjectName, e);
}
}
try {
scheduledExecutor.awaitTermination(2 * this.flushIntervalInSeconds, TimeUnit.SECONDS);
} catch (InterruptedException e) {
addWarn("Exception waiting for termination of LogglyAppender scheduler", e);
}
// stop appender (ie close outputStream) after sending it to Loggly
outputStream.close();
super.stop();
}
/**
* Send log entries to Loggly
*/
@Override
public void processLogEntries() {
if (isDebug()) {
addInfo("Process log entries - " + getDebugInfo());
}
outputStream.rollCurrentBucketIfNotEmpty();
BlockingDeque<ByteArrayOutputStream> filledBuckets = outputStream.getFilledBuckets();
ByteArrayOutputStream bucket;
while ((bucket = filledBuckets.poll()) != null) {
try {
InputStream in = new ByteArrayInputStream(bucket.toByteArray());
processLogEntries(in);
} catch (Exception e) {
addWarn("Internal error", e);
}
outputStream.recycleBucket(bucket);
}
}
/**
* Send log entries to Loggly
*/
protected void processLogEntries(InputStream in) throws IOException {
long nanosBefore = System.nanoTime();
try {
URL url = new URL(endpointUrl);
HttpURLConnection conn;
if (proxy == null) {
conn = (HttpURLConnection) url.openConnection();
} else {
conn = (HttpURLConnection) url.openConnection(proxy);
}
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", layout.getContentType() + "; charset=" + charset.name());
conn.setRequestMethod("POST");
conn.setReadTimeout(getHttpReadTimeoutInMillis());
BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());
long len = IoUtils.copy(in, out);
sentBytes.addAndGet(len);
out.flush();
out.close();
int responseCode = conn.getResponseCode();
String response = super.readResponseBody(conn.getInputStream());
switch (responseCode) {
case HttpURLConnection.HTTP_OK:
case HttpURLConnection.HTTP_ACCEPTED:
sendSuccessCount.incrementAndGet();
break;
default:
sendExceptionCount.incrementAndGet();
addError("LogglyAppender server-side exception: " + responseCode + ": " + response);
}
// force url connection recycling
try {
conn.getInputStream().close();
conn.disconnect();
} catch (Exception e) {
// swallow exception
}
} catch (Exception e) {
sendExceptionCount.incrementAndGet();
addError("LogglyAppender client-side exception", e);
} finally {
sendDurationInNanos.addAndGet(System.nanoTime() - nanosBefore);
}
}
public int getFlushIntervalInSeconds() {
return flushIntervalInSeconds;
}
public void setFlushIntervalInSeconds(int flushIntervalInSeconds) {
this.flushIntervalInSeconds = flushIntervalInSeconds;
}
@Override
public long getSentBytes() {
return sentBytes.get();
}
@Override
public long getSendDurationInNanos() {
return sendDurationInNanos.get();
}
@Override
public int getSendSuccessCount() {
return sendSuccessCount.get();
}
@Override
public int getSendExceptionCount() {
return sendExceptionCount.get();
}
@Override
public int getDiscardedBucketsCount() {
return outputStream.getDiscardedBucketCount();
}
@Override
public long getCurrentLogEntriesBufferSizeInBytes() {
return outputStream.getCurrentOutputStreamSize();
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public boolean isDebug() {
return debug;
}
public void setJmxMonitoring(boolean jmxMonitoring) {
this.jmxMonitoring = jmxMonitoring;
}
public void setMbeanServer(MBeanServer mbeanServer) {
this.mbeanServer = mbeanServer;
}
public void setMaxNumberOfBuckets(int maxNumberOfBuckets) {
this.maxNumberOfBuckets = maxNumberOfBuckets;
}
public void setMaxBucketSizeInKilobytes(int maxBucketSizeInKilobytes) {
this.maxBucketSizeInKilobytes = maxBucketSizeInKilobytes;
}
private String getDebugInfo() {
return "{" +
"sendDurationInMillis=" + TimeUnit.MILLISECONDS.convert(sendDurationInNanos.get(), TimeUnit.NANOSECONDS) +
", sendSuccessCount=" + sendSuccessCount +
", sendExceptionCount=" + sendExceptionCount +
", sentBytes=" + sentBytes +
", discardedBucketsCount=" + getDiscardedBucketsCount() +
", currentLogEntriesBufferSizeInBytes=" + getCurrentLogEntriesBufferSizeInBytes() +
'}';
}
public class LogglyExporter implements Runnable {
@Override
public void run() {
try {
processLogEntries();
} catch (Exception e) {
addWarn("Exception processing log entries", e);
}
}
}
}