Skip to content

Commit 2c0fd9a

Browse files
committed
Increased use of log4j2 readability.
Added a log4j2.xml for tests runs.
1 parent 2d64b1f commit 2c0fd9a

File tree

7 files changed

+43
-57
lines changed

7 files changed

+43
-57
lines changed

src/main/java/org/logstash/beats/BeatsHandler.java

+17-24
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
package org.logstash.beats;
22

3+
import org.apache.logging.log4j.Level;
4+
import org.apache.logging.log4j.LogManager;
5+
import org.apache.logging.log4j.Logger;
6+
37
import io.netty.channel.ChannelHandlerContext;
48
import io.netty.channel.SimpleChannelInboundHandler;
59
import io.netty.util.AttributeKey;
@@ -10,7 +14,8 @@
1014
import javax.net.ssl.SSLHandshakeException;
1115

1216
public class BeatsHandler extends SimpleChannelInboundHandler<Batch> {
13-
private final static Logger logger = LogManager.getLogger(BeatsHandler.class);
17+
18+
private final static Logger logger = LogManager.getLogger();
1419
private final IMessageListener messageListener;
1520
private ChannelHandlerContext context;
1621

@@ -22,33 +27,25 @@ public BeatsHandler(IMessageListener listener) {
2227
@Override
2328
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
2429
context = ctx;
25-
if (logger.isTraceEnabled()){
26-
logger.trace(format("Channel Active"));
27-
}
30+
logger.trace("{}", () -> format("Channel Active"));
2831
super.channelActive(ctx);
2932
messageListener.onNewConnection(ctx);
3033
}
3134

3235
@Override
3336
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
3437
super.channelInactive(ctx);
35-
if (logger.isTraceEnabled()){
36-
logger.trace(format("Channel Inactive"));
37-
}
38+
logger.trace("{}", () -> format("Channel Inactive"));
3839
messageListener.onConnectionClose(ctx);
3940
}
4041

4142

4243
@Override
4344
public void channelRead0(ChannelHandlerContext ctx, Batch batch) throws Exception {
44-
if(logger.isDebugEnabled()) {
45-
logger.debug(format("Received a new payload"));
46-
}
45+
logger.debug("{}", () -> format("Received a new payload"));
4746
try {
4847
for (Message message : batch) {
49-
if (logger.isDebugEnabled()) {
50-
logger.debug(format("Sending a new message for the listener, sequence: " + message.getSequence()));
51-
}
48+
logger.debug("{}", () -> format("Sending a new message for the listener, sequence: " + message.getSequence()));
5249
messageListener.onNewMessage(ctx, message);
5350

5451
if (needAck(message)) {
@@ -58,9 +55,9 @@ public void channelRead0(ChannelHandlerContext ctx, Batch batch) throws Exceptio
5855
}finally{
5956
//this channel is done processing this payload, instruct the connection handler to stop sending TCP keep alive
6057
ctx.channel().attr(ConnectionHandler.CHANNEL_SEND_KEEP_ALIVE).get().set(false);
61-
if (logger.isDebugEnabled()) {
62-
logger.debug("{}: batches pending: {}", ctx.channel().id().asShortText(),ctx.channel().attr(ConnectionHandler.CHANNEL_SEND_KEEP_ALIVE).get().get());
63-
}
58+
logger.debug("{}: batches pending: {}",
59+
() -> ctx.channel().id().asShortText(),
60+
() -> ctx.channel().attr(ConnectionHandler.CHANNEL_SEND_KEEP_ALIVE).get().get());
6461
batch.release();
6562
ctx.flush();
6663
}
@@ -83,11 +80,9 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E
8380
}
8481
String causeMessage = cause.getMessage() == null ? cause.getClass().toString() : cause.getMessage();
8582

86-
if (logger.isDebugEnabled()){
87-
logger.debug(format("Handling exception: " + causeMessage), cause);
88-
}
89-
logger.info(format("Handling exception: " + causeMessage));
90-
} finally{
83+
logger.info("{}", () -> format("Handling exception: " + causeMessage));
84+
logger.catching(Level.DEBUG, cause);
85+
} finally {
9186
super.exceptionCaught(ctx, cause);
9287
ctx.flush();
9388
ctx.close();
@@ -99,9 +94,7 @@ private boolean needAck(Message message) {
9994
}
10095

10196
private void ack(ChannelHandlerContext ctx, Message message) {
102-
if (logger.isTraceEnabled()){
103-
logger.trace(format("Acking message number " + message.getSequence()));
104-
}
97+
logger.trace("{}", () -> format("Acking message number " + message.getSequence()));
10598
writeAck(ctx, message.getBatch().getProtocol(), message.getSequence());
10699
}
107100

src/main/java/org/logstash/beats/BeatsParser.java

+4-7
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@
1818

1919

2020
public class BeatsParser extends ByteToMessageDecoder {
21-
private final static Logger logger = LogManager.getLogger(BeatsParser.class);
21+
22+
private static final Logger logger = LogManager.getLogger();
2223

2324
private Batch batch;
2425

@@ -195,9 +196,7 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) t
195196
logger.trace("Running: READ_JSON");
196197
((V2Batch)batch).addMessage(sequence, in, requiredBytes);
197198
if(batch.isComplete()) {
198-
if(logger.isTraceEnabled()) {
199-
logger.trace("Sending batch size: " + this.batch.size() + ", windowSize: " + batch.getBatchSize() + " , seq: " + sequence);
200-
}
199+
logger.trace("Sending batch size: {}, windowSize: {}, seq: {}", () -> batch.size(), () -> batch.getBatchSize() , () -> sequence);
201200
out.add(batch);
202201
batchComplete();
203202
}
@@ -217,9 +216,7 @@ private void transition(States next) {
217216
}
218217

219218
private void transition(States nextState, int requiredBytes) {
220-
if(logger.isTraceEnabled()) {
221-
logger.trace("Transition, from: " + currentState + ", to: " + nextState + ", requiring " + requiredBytes + " bytes");
222-
}
219+
logger.trace("{}", () -> "Transition, from: " + currentState + ", to: " + nextState + ", requiring " + requiredBytes + " bytes");
223220
this.currentState = nextState;
224221
this.requiredBytes = requiredBytes;
225222
}

src/main/java/org/logstash/beats/ConnectionHandler.java

+8-8
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,15 @@
1616
* Manages the connection state to the beats client.
1717
*/
1818
public class ConnectionHandler extends ChannelDuplexHandler {
19-
private final static Logger logger = LogManager.getLogger(ConnectionHandler.class);
19+
20+
private final static Logger logger = LogManager.getLogger();
2021

2122
public static AttributeKey<AtomicBoolean> CHANNEL_SEND_KEEP_ALIVE = AttributeKey.valueOf("channel-send-keep-alive");
2223

2324
@Override
2425
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
2526
ctx.channel().attr(CHANNEL_SEND_KEEP_ALIVE).set(new AtomicBoolean(false));
26-
if (logger.isTraceEnabled()) {
27-
logger.trace("{}: channel activated", ctx.channel().id().asShortText());
28-
}
27+
logger.trace("{}: channel activated", () -> ctx.channel().id().asShortText());
2928
super.channelActive(ctx);
3029
}
3130

@@ -37,9 +36,9 @@ public void channelActive(final ChannelHandlerContext ctx) throws Exception {
3736
@Override
3837
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
3938
ctx.channel().attr(CHANNEL_SEND_KEEP_ALIVE).get().set(true);
40-
if (logger.isDebugEnabled()) {
41-
logger.debug("{}: batches pending: {}", ctx.channel().id().asShortText(),ctx.channel().attr(CHANNEL_SEND_KEEP_ALIVE).get().get());
42-
}
39+
logger.debug("{}: batches pending: {}",
40+
() -> ctx.channel().id().asShortText(),
41+
() -> ctx.channel().attr(CHANNEL_SEND_KEEP_ALIVE).get().get());
4342
super.channelRead(ctx, msg);
4443
}
4544

@@ -80,7 +79,8 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc
8079
}
8180
}
8281
} else if (e.state() == IdleState.ALL_IDLE) {
83-
logger.debug("{}: reader and writer are idle, closing remote connection", ctx.channel().id().asShortText());
82+
logger.debug("{}: reader and writer are idle, closing remote connection",
83+
() -> ctx.channel().id().asShortText());
8484
ctx.flush();
8585
ChannelFuture f = ctx.close();
8686
if (logger.isTraceEnabled()) {

src/main/java/org/logstash/beats/MessageListener.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
*/
1313
// This need to be implemented in Ruby
1414
public class MessageListener implements IMessageListener {
15-
private final static Logger logger = LogManager.getLogger(MessageListener.class);
15+
16+
private static final Logger logger = LogManager.getLogger();
1617

1718

1819
/**

src/main/java/org/logstash/beats/Runner.java

+1-3
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,7 @@
88
public class Runner {
99
private static final int DEFAULT_PORT = 5044;
1010

11-
private final static Logger logger = LogManager.getLogger(Runner.class);
12-
13-
11+
private static final Logger logger = LogManager.getLogger();
1412

1513
static public void main(String[] args) throws Exception {
1614
logger.info("Starting Beats Bulk");

src/main/java/org/logstash/beats/Server.java

+3-2
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@
1818
import java.security.cert.CertificateException;
1919

2020
public class Server {
21-
private final static Logger logger = LogManager.getLogger(Server.class);
21+
22+
private static final Logger logger = LogManager.getLogger();
2223

2324
private final int port;
2425
private final String host;
@@ -52,7 +53,7 @@ public Server listen() throws InterruptedException {
5253
}
5354
workGroup = new NioEventLoopGroup();
5455
try {
55-
logger.info("Starting server on port: {}", this.port);
56+
logger.info("Starting server on port: {}", port);
5657

5758
beatsInitializer = new BeatsInitializer(isSslEnable(), messageListener, clientInactivityTimeoutSeconds, beatsHeandlerThreadCount);
5859

src/main/java/org/logstash/netty/SslSimpleBuilder.java

+8-12
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public static enum SslClientVerifyMode {
3030
VERIFY_PEER,
3131
FORCE_PEER,
3232
}
33-
private final static Logger logger = LogManager.getLogger(SslSimpleBuilder.class);
33+
private static final Logger logger = LogManager.getLogger();
3434

3535

3636
private File sslKeyFile;
@@ -77,7 +77,7 @@ public SslSimpleBuilder setCipherSuites(String[] ciphersSuite) throws IllegalArg
7777
if(!OpenSsl.isCipherSuiteAvailable(cipher)) {
7878
throw new IllegalArgumentException("Cipher `" + cipher + "` is not available");
7979
} else {
80-
logger.debug("Cipher is supported: " + cipher);
80+
logger.debug("Cipher is supported: {}", cipher);
8181
}
8282
}
8383

@@ -111,25 +111,21 @@ public File getSslCertificateFile() {
111111
public SslHandler build(ByteBufAllocator bufferAllocator) throws IOException, NoSuchAlgorithmException, CertificateException {
112112
SslContextBuilder builder = SslContextBuilder.forServer(sslCertificateFile, sslKeyFile, passPhrase);
113113

114-
if(logger.isDebugEnabled())
115-
logger.debug("Available ciphers:" + Arrays.toString(OpenSsl.availableOpenSslCipherSuites().toArray()));
116-
logger.debug("Ciphers: " + Arrays.toString(ciphers));
114+
logger.debug("Available ciphers: {}", () ->Arrays.toString(OpenSsl.availableOpenSslCipherSuites().toArray()));
115+
logger.debug("Ciphers: {}", () -> Arrays.toString(ciphers));
117116

118117

119118
builder.ciphers(Arrays.asList(ciphers));
120119

121-
if(requireClientAuth()) {
122-
if (logger.isDebugEnabled())
123-
logger.debug("Certificate Authorities: " + Arrays.toString(certificateAuthorities));
124-
120+
if (requireClientAuth()) {
121+
logger.debug("Certificate Authorities: {}", () -> Arrays.toString(certificateAuthorities));
125122
builder.trustManager(loadCertificateCollection(certificateAuthorities));
126123
}
127124

128125
SslContext context = builder.build();
129126
SslHandler sslHandler = context.newHandler(bufferAllocator);
130127

131-
if(logger.isDebugEnabled())
132-
logger.debug("TLS: " + Arrays.toString(protocols));
128+
logger.debug("TLS: {}", () -> Arrays.toString(protocols));
133129

134130
SSLEngine engine = sslHandler.engine();
135131
engine.setEnabledProtocols(protocols);
@@ -162,7 +158,7 @@ private X509Certificate[] loadCertificateCollection(String[] certificates) throw
162158
for(int i = 0; i < certificates.length; i++) {
163159
String certificate = certificates[i];
164160

165-
logger.debug("Loading certificates from file " + certificate);
161+
logger.debug("Loading certificates from file {}", ()-> certificate);
166162

167163
try(InputStream in = new FileInputStream(certificate)) {
168164
List<X509Certificate> certificatesChains = (List<X509Certificate>) certificateFactory.generateCertificates(in);

0 commit comments

Comments
 (0)