-
Notifications
You must be signed in to change notification settings - Fork 214
/
FluentPublishingConnectionLogger.java
327 lines (287 loc) · 14.3 KB
/
FluentPublishingConnectionLogger.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
/*
* Copyright (c) 2021 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.ditto.connectivity.service.messaging.monitoring.logs;
import static org.eclipse.ditto.base.model.common.ConditionChecker.checkNotNull;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import javax.annotation.Nullable;
import org.eclipse.ditto.connectivity.model.ConnectionId;
import org.eclipse.ditto.connectivity.model.LogCategory;
import org.eclipse.ditto.connectivity.model.LogEntry;
import org.eclipse.ditto.connectivity.model.LogLevel;
import org.eclipse.ditto.connectivity.model.LogType;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.ConnectionMonitor;
import org.eclipse.ditto.internal.utils.akka.logging.DittoLoggerFactory;
import org.eclipse.ditto.internal.utils.akka.logging.ThreadSafeDittoLogger;
import org.eclipse.ditto.json.JsonFieldDefinition;
import org.komamitsu.fluency.BufferFullException;
import org.komamitsu.fluency.EventTime;
import org.komamitsu.fluency.Fluency;
/**
* Implementation of {@link ConnectionLogger} that publishes logs via {@link Fluency} library to a Fluentd/Fluentbit
* endpoint.
*/
final class FluentPublishingConnectionLogger
extends AbstractConnectionLogger<FluentPublishingConnectionLogger.Builder, FluentPublishingConnectionLogger> {
private static final ThreadSafeDittoLogger LOGGER =
DittoLoggerFactory.getThreadSafeLogger(FluentPublishingConnectionLogger.class);
private static final String TAG_CONNECTION_ID = "connectionId";
private static final String TAG_LEVEL = toTag(LogEntry.JsonFields.LEVEL);
private static final String TAG_CATEGORY = toTag(LogEntry.JsonFields.CATEGORY);
private static final String TAG_TYPE = toTag(LogEntry.JsonFields.TYPE);
private static final String TAG_CORRELATION_ID = toTag(LogEntry.JsonFields.CORRELATION_ID);
private static final String TAG_ADDRESS = toTag(LogEntry.JsonFields.ADDRESS);
private static final String TAG_ENTITY_TYPE = "entityType";
private static final String TAG_ENTITY_ID = toTag(LogEntry.JsonFields.ENTITY_ID);
private static final String TAG_MESSAGE = toTag(LogEntry.JsonFields.MESSAGE);
private static final String TAG_INSTANCE_ID = "instanceId";
private static String toTag(final JsonFieldDefinition<String> level) {
return level.getPointer().get(0).orElseThrow().toString();
}
private final ConnectionId connectionId;
private final String fluentTag;
private final Set<LogLevel> logLevels;
private final Fluency fluencyForwarder;
private final Duration waitUntilAllBufferFlushedDurationOnClose;
private final Map<String, Object> additionalLogContext;
@Nullable private final String instanceIdentifier;
FluentPublishingConnectionLogger(final Builder builder) {
super(builder);
connectionId = builder.connectionId;
fluentTag = builder.fluentTag;
logLevels = builder.logLevels;
fluencyForwarder = builder.fluencyForwarder;
waitUntilAllBufferFlushedDurationOnClose = builder.waitUntilAllBufferFlushedDurationOnClose;
additionalLogContext = Map.copyOf(builder.additionalLogContext);
instanceIdentifier = builder.instanceIdentifier;
}
/**
* Create a new builder.
*
* @param connectionId the {@code ConnectionId} of the logged connection.
* @param category category of logs stored by the logger.
* @param type type of logs stored by the logger.
* @param fluencyForwarder the {@code Fluency} forwarder used to forward logs to fluentd/fluentbit.
* @param waitUntilAllBufferFlushedDurationOnClose the duration of how long to wait after closing the Fluency buffer.
* @return a new Builder for {@code FluentPublishingConnectionLogger}.
* @throws java.lang.NullPointerException if any non-nullable argument is {@code null}.
*/
static Builder newBuilder(final ConnectionId connectionId, final LogCategory category,
final LogType type,
final Fluency fluencyForwarder,
final Duration waitUntilAllBufferFlushedDurationOnClose) {
return new Builder(connectionId, category, type, fluencyForwarder, waitUntilAllBufferFlushedDurationOnClose);
}
@Override
public Collection<LogEntry> getLogs() {
return Collections.emptyList();
}
@Override
public void clear() {
// no-op
}
@Override
public void close() throws IOException {
LOGGER.info("Flushing and closing Fluency forwarder, waiting <{}> for buffers being flushed...",
waitUntilAllBufferFlushedDurationOnClose);
// fluencyForwarder.close also flushes:
fluencyForwarder.close();
if (!waitUntilAllBufferFlushedDurationOnClose.isZero() &&
!waitUntilAllBufferFlushedDurationOnClose.isNegative()) {
try {
fluencyForwarder.waitUntilAllBufferFlushed((int) waitUntilAllBufferFlushedDurationOnClose.getSeconds());
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
@Override
public void success(final ConnectionMonitor.InfoProvider infoProvider, final String message,
final Object... messageArguments) {
emitLogEntry(infoProvider, message, messageArguments, LogLevel.SUCCESS);
}
@Override
public void failure(final ConnectionMonitor.InfoProvider infoProvider, final String message,
final Object... messageArguments) {
emitLogEntry(infoProvider, message, messageArguments, LogLevel.FAILURE);
}
@Override
public void exception(final ConnectionMonitor.InfoProvider infoProvider, final String message,
final Object... messageArguments) {
emitLogEntry(infoProvider, message, messageArguments, LogLevel.FAILURE);
}
@Override
public void logEntry(final LogEntry logEntry) {
emitLogEntry(logEntry);
}
private void emitLogEntry(final ConnectionMonitor.InfoProvider infoProvider, final String message,
final Object[] messageArguments, final LogLevel logLevel) {
final String formattedMessage = formatMessage(infoProvider, message, messageArguments);
emitLogEntry(getLogEntry(infoProvider, formattedMessage, logLevel));
}
private void emitLogEntry(final LogEntry logEntry) {
final String correlationId = InfoProviderFactory.FALLBACK_CORRELATION_ID
.equals(logEntry.getCorrelationId()) ? null : logEntry.getCorrelationId();
if (logLevels.contains(logEntry.getLogLevel())) {
try {
final Instant timestamp = logEntry.getTimestamp();
final EventTime eventTime = EventTime.fromEpoch(timestamp.getEpochSecond(), timestamp.getNano());
final Map<String, Object> logMap = new LinkedHashMap<>();
logMap.put(TAG_CONNECTION_ID, connectionId.toString());
logMap.put(TAG_LEVEL, logEntry.getLogLevel().toString());
logMap.put(TAG_CATEGORY, logEntry.getLogCategory().toString());
logMap.put(TAG_TYPE, logEntry.getLogType().toString());
if (null != correlationId) {
logMap.put(TAG_CORRELATION_ID, correlationId);
}
logEntry.getAddress().ifPresent(address -> logMap.put(TAG_ADDRESS, address));
logEntry.getEntityId().ifPresent(entityId -> {
logMap.put(TAG_ENTITY_TYPE, entityId.getEntityType().toString());
logMap.put(TAG_ENTITY_ID, entityId.toString());
});
logMap.put(TAG_MESSAGE, logEntry.getMessage());
if (null != instanceIdentifier) {
logMap.put(TAG_INSTANCE_ID, instanceIdentifier);
}
logMap.putAll(additionalLogContext);
fluencyForwarder.emit(fluentTag, eventTime, logMap);
} catch (final BufferFullException e) {
LOGGER.withCorrelationId(correlationId)
.error("Got BufferFullException when trying to emit further connection log entries to fluentd: {}",
e.getMessage());
} catch (final IOException e) {
LOGGER.withCorrelationId(correlationId)
.error("Got IOException when trying to emit further connection log entries to fluentd: <{}>: {}",
e.getClass().getSimpleName(), e.getMessage());
}
} else {
LOGGER.withCorrelationId(correlationId)
.debug("Not emitting log entry with logLevel <{}> as the configured logLevels contained: <{}>",
logEntry.getLogLevel(), logLevels);
}
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) return false;
final FluentPublishingConnectionLogger that = (FluentPublishingConnectionLogger) o;
return Objects.equals(connectionId, that.connectionId) &&
Objects.equals(fluentTag, that.fluentTag) &&
Objects.equals(logLevels, that.logLevels) &&
Objects.equals(fluencyForwarder, that.fluencyForwarder) &&
Objects.equals(additionalLogContext, that.additionalLogContext) &&
Objects.equals(instanceIdentifier, that.instanceIdentifier);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), connectionId, fluentTag, logLevels, fluencyForwarder,
additionalLogContext, instanceIdentifier);
}
@Override
public String toString() {
return getClass().getSimpleName() + " [" + super.toString() +
", connectionId=" + connectionId +
", fluentTag=" + fluentTag +
", logLevels=" + logLevels +
", fluencyForwarder=" + fluencyForwarder +
", additionalLogContext=" + additionalLogContext +
", instanceIdentifier=" + instanceIdentifier +
"]";
}
/**
* Builder for {@code FluentPublishingConnectionLogger}.
*/
static final class Builder extends AbstractConnectionLoggerBuilder
<FluentPublishingConnectionLogger.Builder, FluentPublishingConnectionLogger> {
private static final String CONNECTION_TAG_PREFIX = "connection:";
final ConnectionId connectionId;
String fluentTag;
Set<LogLevel> logLevels;
final Fluency fluencyForwarder;
final Duration waitUntilAllBufferFlushedDurationOnClose;
Map<String, Object> additionalLogContext;
@Nullable String instanceIdentifier;
private Builder(final ConnectionId connectionId,
final LogCategory category,
final LogType type,
final Fluency fluencyForwarder,
final Duration waitUntilAllBufferFlushedDurationOnClose) {
super(category, type);
this.connectionId = connectionId;
this.fluentTag = CONNECTION_TAG_PREFIX + connectionId; // default to the connectionId as tag
this.fluencyForwarder = fluencyForwarder;
this.waitUntilAllBufferFlushedDurationOnClose = waitUntilAllBufferFlushedDurationOnClose;
this.additionalLogContext = Collections.emptyMap();
}
/**
* Use the provided {@code fluentTag} for the built {@code FluentPublishingConnectionLogger}.
*
* @param fluentTag the tag to use when forwarding logs to fluentd/fluentbit.
* @return the builder for method chaining.
* @throws NullPointerException if the passed {@code fluentTag} was {@code null}.
*/
Builder withFluentTag(final CharSequence fluentTag) {
this.fluentTag = checkNotNull(fluentTag, "fluentTag").toString();
return this;
}
/**
* Use the provided {@code logLevels}, only log entries in those levels will be published.
*
* @param logLevels the log levels to include for the log publishing.
* @return the builder for method chaining.
* @throws NullPointerException if the passed {@code logLevel} was {@code null}.
*/
Builder withLogLevels(final Collection<LogLevel> logLevels) {
this.logLevels = Set.copyOf(checkNotNull(logLevels, "logLevels"));
return this;
}
/**
* Use the provided {@code additionalLogContext} for the built {@code FluentPublishingConnectionLogger}.
*
* @param additionalLogContext the map of additional entries to emit for each forwarded log entry.
* @return the builder for method chaining.
* @throws NullPointerException if the passed {@code additionalLogContext} was {@code null}.
*/
Builder withAdditionalLogContext(final Map<String, Object> additionalLogContext) {
this.additionalLogContext = checkNotNull(additionalLogContext, "additionalLogContext");
return this;
}
/**
* Use the provided {@code instanceIdentifier} for the built {@code FluentPublishingConnectionLogger}.
*
* @param instanceIdentifier the identifier of the connectivity instance.
* @return the builder for method chaining.
* @throws NullPointerException if the passed {@code instanceIdentifier} was {@code null}.
*/
Builder withInstanceIdentifier(final CharSequence instanceIdentifier) {
this.instanceIdentifier = checkNotNull(instanceIdentifier, "instanceIdentifier").toString();
return this;
}
@Override
public FluentPublishingConnectionLogger build() {
return new FluentPublishingConnectionLogger(this);
}
}
}