From 8cbd4feaf04d6cd76b715a1017eae067a3ad4d27 Mon Sep 17 00:00:00 2001 From: Artem Vysochyn Date: Sat, 25 Jan 2025 21:47:52 +0200 Subject: [PATCH] Set back slf4j, + added LoggingExtension --- cluster-testlib/pom.xml | 53 +++++- .../cluster/utils/LoggingExtension.java | 54 ++++++ .../cluster/utils/NetworkEmulator.java | 34 ++-- .../org.junit.jupiter.api.extension.Extension | 1 + .../main/resources/junit-platform.properties | 1 + .../src/main/resources/log4j2.xml | 0 .../io/scalecube/cluster/utils/BaseTest.java | 23 --- .../cluster/utils/NetworkEmulatorTest.java | 2 +- cluster/pom.xml | 4 + .../io/scalecube/cluster/ClusterImpl.java | 52 ++---- .../fdetector/FailureDetectorImpl.java | 135 +++++---------- .../cluster/gossip/GossipProtocolImpl.java | 62 ++----- .../membership/MembershipProtocolImpl.java | 155 +++++++----------- .../cluster/metadata/MetadataStoreImpl.java | 63 +++---- .../java/io/scalecube/cluster/BaseTest.java | 20 +-- .../io/scalecube/cluster/ClusterTest.java | 16 +- .../cluster/gossip/GossipProtocolTest.java | 48 ++---- codec-parent/pom.xml | 11 +- examples/pom.xml | 12 -- examples/src/main/resources/log4j2.xml | 28 ---- pom.xml | 58 +------ transport-parent/pom.xml | 4 + .../transport/netty/TransportImpl.java | 57 +++---- .../scalecube/transport/netty/BaseTest.java | 27 +-- .../netty/tcp/TcpTransportSendOrderTest.java | 32 ++-- .../transport/netty/tcp/TcpTransportTest.java | 19 +-- .../WebsocketTransportSendOrderTest.java | 32 ++-- .../websocket/WebsocketTransportTest.java | 19 +-- 28 files changed, 406 insertions(+), 616 deletions(-) create mode 100644 cluster-testlib/src/main/java/io/scalecube/cluster/utils/LoggingExtension.java create mode 100644 cluster-testlib/src/main/resources/META-INF/services/org.junit.jupiter.api.extension.Extension create mode 100644 cluster-testlib/src/main/resources/junit-platform.properties rename cluster/src/test/resources/log4j2-test.xml => cluster-testlib/src/main/resources/log4j2.xml (100%) delete mode 100644 cluster-testlib/src/test/java/io/scalecube/cluster/utils/BaseTest.java delete mode 100644 examples/src/main/resources/log4j2.xml diff --git a/cluster-testlib/pom.xml b/cluster-testlib/pom.xml index 9a9e6daa..45e8760b 100644 --- a/cluster-testlib/pom.xml +++ b/cluster-testlib/pom.xml @@ -1,5 +1,7 @@ - + scalecube-cluster-parent io.scalecube @@ -21,6 +23,55 @@ scalecube-cluster-api ${project.version} + + + org.slf4j + slf4j-api + + + org.apache.logging.log4j + log4j-slf4j-impl + + + org.apache.logging.log4j + log4j-core + + + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + + + org.junit.jupiter + junit-jupiter-params + ${junit-jupiter.version} + + + org.mockito + mockito-junit-jupiter + ${mockito-junit.version} + + + org.junit.jupiter + junit-jupiter-api + + + + + org.hamcrest + hamcrest-all + ${hamcrest.version} + + + io.projectreactor + reactor-test + diff --git a/cluster-testlib/src/main/java/io/scalecube/cluster/utils/LoggingExtension.java b/cluster-testlib/src/main/java/io/scalecube/cluster/utils/LoggingExtension.java new file mode 100644 index 00000000..5308441e --- /dev/null +++ b/cluster-testlib/src/main/java/io/scalecube/cluster/utils/LoggingExtension.java @@ -0,0 +1,54 @@ +package io.scalecube.cluster.utils; + +import java.lang.reflect.Method; +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LoggingExtension + implements AfterEachCallback, BeforeEachCallback, AfterAllCallback, BeforeAllCallback { + + private static final Logger LOGGER = LoggerFactory.getLogger(LoggingExtension.class); + + @Override + public void beforeAll(ExtensionContext context) { + LOGGER.info( + "***** Setup: " + context.getTestClass().map(Class::getSimpleName).orElse("") + " *****"); + } + + @Override + public void afterEach(ExtensionContext context) { + LOGGER.info( + "***** Test finished: " + + context.getTestClass().map(Class::getSimpleName).orElse("") + + "." + + context.getTestMethod().map(Method::getName).orElse("") + + "." + + context.getDisplayName() + + " *****"); + } + + @Override + public void beforeEach(ExtensionContext context) { + LOGGER.info( + "***** Test started: " + + context.getTestClass().map(Class::getSimpleName).orElse("") + + "." + + context.getTestMethod().map(Method::getName).orElse("") + + "." + + context.getDisplayName() + + " *****"); + } + + @Override + public void afterAll(ExtensionContext context) { + LOGGER.info( + "***** TearDown: " + + context.getTestClass().map(Class::getSimpleName).orElse("") + + " *****"); + } +} diff --git a/cluster-testlib/src/main/java/io/scalecube/cluster/utils/NetworkEmulator.java b/cluster-testlib/src/main/java/io/scalecube/cluster/utils/NetworkEmulator.java index 030081e3..552c10bc 100644 --- a/cluster-testlib/src/main/java/io/scalecube/cluster/utils/NetworkEmulator.java +++ b/cluster-testlib/src/main/java/io/scalecube/cluster/utils/NetworkEmulator.java @@ -1,8 +1,6 @@ package io.scalecube.cluster.utils; import io.scalecube.cluster.transport.api.Message; -import java.lang.System.Logger; -import java.lang.System.Logger.Level; import java.time.Duration; import java.util.Arrays; import java.util.Collection; @@ -11,6 +9,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicLong; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; /** @@ -24,7 +24,7 @@ */ public final class NetworkEmulator { - private static final Logger LOGGER = System.getLogger(NetworkEmulator.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(NetworkEmulator.class); private volatile OutboundSettings defaultOutboundSettings = new OutboundSettings(0, 0); private volatile InboundSettings defaultInboundSettings = new InboundSettings(true); @@ -69,8 +69,7 @@ public OutboundSettings outboundSettings(String destination) { public void outboundSettings(String destination, int lossPercent, int meanDelay) { OutboundSettings settings = new OutboundSettings(lossPercent, meanDelay); outboundSettings.put(destination, settings); - LOGGER.log( - Level.DEBUG, "[{0}] Set outbound settings {1} to {2}", address, settings, destination); + LOGGER.debug("[{}] Set outbound settings {} to {}", address, settings, destination); } /** @@ -81,22 +80,21 @@ public void outboundSettings(String destination, int lossPercent, int meanDelay) */ public void setDefaultOutboundSettings(int lossPercent, int meanDelay) { defaultOutboundSettings = new OutboundSettings(lossPercent, meanDelay); - LOGGER.log( - Level.DEBUG, "[{0}] Set default outbound settings {1}", address, defaultOutboundSettings); + LOGGER.debug("[{}] Set default outbound settings {}", address, defaultOutboundSettings); } /** Blocks outbound messages to all destinations. */ public void blockAllOutbound() { outboundSettings.clear(); setDefaultOutboundSettings(100, 0); - LOGGER.log(Level.DEBUG, "[{0}] Blocked outbound to all destinations", address); + LOGGER.debug("[{}] Blocked outbound to all destinations", address); } /** Unblocks outbound messages to all destinations. */ public void unblockAllOutbound() { outboundSettings.clear(); setDefaultOutboundSettings(0, 0); - LOGGER.log(Level.DEBUG, "[{0}] Unblocked outbound to all destinations", address); + LOGGER.debug("[{}] Unblocked outbound to all destinations", address); } /** @@ -117,7 +115,7 @@ public void blockOutbound(Collection destinations) { for (String destination : destinations) { outboundSettings.put(destination, new OutboundSettings(100, 0)); } - LOGGER.log(Level.DEBUG, "[{0}] Blocked outbound to {1}", address, destinations); + LOGGER.debug("[{}] Blocked outbound to {}", address, destinations); } /** @@ -136,7 +134,7 @@ public void unblockOutbound(String... destinations) { */ public void unblockOutbound(Collection destinations) { destinations.forEach(outboundSettings::remove); - LOGGER.log(Level.DEBUG, "[{0}] Unblocked outbound {1}", address, destinations); + LOGGER.debug("[{}] Unblocked outbound {}", address, destinations); } /** @@ -222,8 +220,7 @@ public InboundSettings inboundSettings(String destination) { public void inboundSettings(String destination, boolean shallPass) { InboundSettings settings = new InboundSettings(shallPass); inboundSettings.put(destination, settings); - LOGGER.log( - Level.DEBUG, "[{0}] Set inbound settings {1} to {2}", address, settings, destination); + LOGGER.debug("[{}] Set inbound settings {} to {}", address, settings, destination); } /** @@ -233,22 +230,21 @@ public void inboundSettings(String destination, boolean shallPass) { */ public void setDefaultInboundSettings(boolean shallPass) { defaultInboundSettings = new InboundSettings(shallPass); - LOGGER.log( - Level.DEBUG, "[{0}] Set default inbound settings {1}", address, defaultInboundSettings); + LOGGER.debug("[{}] Set default inbound settings {}", address, defaultInboundSettings); } /** Blocks inbound messages from all destinations. */ public void blockAllInbound() { inboundSettings.clear(); setDefaultInboundSettings(false); - LOGGER.log(Level.DEBUG, "[{0}] Blocked inbound from all destinations", address); + LOGGER.debug("[{}] Blocked inbound from all destinations", address); } /** Unblocks inbound messages to all destinations. */ public void unblockAllInbound() { inboundSettings.clear(); setDefaultInboundSettings(true); - LOGGER.log(Level.DEBUG, "[{0}] Unblocked inbound from all destinations", address); + LOGGER.debug("[{}] Unblocked inbound from all destinations", address); } /** @@ -269,7 +265,7 @@ public void blockInbound(Collection destinations) { for (String destination : destinations) { inboundSettings.put(destination, new InboundSettings(false)); } - LOGGER.log(Level.DEBUG, "[{0}] Blocked inbound from {1}", address, destinations); + LOGGER.debug("[{}] Blocked inbound from {}", address, destinations); } /** @@ -288,7 +284,7 @@ public void unblockInbound(String... destinations) { */ public void unblockInbound(Collection destinations) { destinations.forEach(inboundSettings::remove); - LOGGER.log(Level.DEBUG, "[{0}] Unblocked inbound from {1}", address, destinations); + LOGGER.debug("[{}] Unblocked inbound from {}", address, destinations); } /** diff --git a/cluster-testlib/src/main/resources/META-INF/services/org.junit.jupiter.api.extension.Extension b/cluster-testlib/src/main/resources/META-INF/services/org.junit.jupiter.api.extension.Extension new file mode 100644 index 00000000..122d0873 --- /dev/null +++ b/cluster-testlib/src/main/resources/META-INF/services/org.junit.jupiter.api.extension.Extension @@ -0,0 +1 @@ +io.scalecube.cluster.utils.LoggingExtension diff --git a/cluster-testlib/src/main/resources/junit-platform.properties b/cluster-testlib/src/main/resources/junit-platform.properties new file mode 100644 index 00000000..6efc0d5e --- /dev/null +++ b/cluster-testlib/src/main/resources/junit-platform.properties @@ -0,0 +1 @@ +junit.jupiter.extensions.autodetection.enabled=true diff --git a/cluster/src/test/resources/log4j2-test.xml b/cluster-testlib/src/main/resources/log4j2.xml similarity index 100% rename from cluster/src/test/resources/log4j2-test.xml rename to cluster-testlib/src/main/resources/log4j2.xml diff --git a/cluster-testlib/src/test/java/io/scalecube/cluster/utils/BaseTest.java b/cluster-testlib/src/test/java/io/scalecube/cluster/utils/BaseTest.java deleted file mode 100644 index 610c017b..00000000 --- a/cluster-testlib/src/test/java/io/scalecube/cluster/utils/BaseTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.scalecube.cluster.utils; - -import java.lang.System.Logger; -import java.lang.System.Logger.Level; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.TestInfo; - -/** Base test class. */ -public class BaseTest { - - protected static final Logger LOGGER = System.getLogger(BaseTest.class.getName()); - - @BeforeEach - public final void baseSetUp(TestInfo testInfo) { - LOGGER.log(Level.INFO, "***** Test started : " + testInfo.getDisplayName() + " *****"); - } - - @AfterEach - public final void baseTearDown(TestInfo testInfo) { - LOGGER.log(Level.INFO, "***** Test finished : " + testInfo.getDisplayName() + " *****"); - } -} diff --git a/cluster-testlib/src/test/java/io/scalecube/cluster/utils/NetworkEmulatorTest.java b/cluster-testlib/src/test/java/io/scalecube/cluster/utils/NetworkEmulatorTest.java index b65137db..3d3c6567 100644 --- a/cluster-testlib/src/test/java/io/scalecube/cluster/utils/NetworkEmulatorTest.java +++ b/cluster-testlib/src/test/java/io/scalecube/cluster/utils/NetworkEmulatorTest.java @@ -4,7 +4,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class NetworkEmulatorTest extends BaseTest { +public class NetworkEmulatorTest { @Test public void testResolveLinkSettingsBySocketAddress() { diff --git a/cluster/pom.xml b/cluster/pom.xml index d9666d18..ce72fedd 100644 --- a/cluster/pom.xml +++ b/cluster/pom.xml @@ -24,6 +24,10 @@ scalecube-cluster-api ${project.version} + + org.slf4j + slf4j-api + diff --git a/cluster/src/main/java/io/scalecube/cluster/ClusterImpl.java b/cluster/src/main/java/io/scalecube/cluster/ClusterImpl.java index 566cfe03..ff2a9608 100644 --- a/cluster/src/main/java/io/scalecube/cluster/ClusterImpl.java +++ b/cluster/src/main/java/io/scalecube/cluster/ClusterImpl.java @@ -19,8 +19,6 @@ import io.scalecube.cluster.transport.api.TransportConfig; import io.scalecube.cluster.transport.api.TransportFactory; import java.io.Serializable; -import java.lang.System.Logger; -import java.lang.System.Logger.Level; import java.nio.ByteBuffer; import java.time.Duration; import java.util.Collection; @@ -37,6 +35,8 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import reactor.core.Disposable; import reactor.core.Disposables; import reactor.core.publisher.Flux; @@ -45,10 +45,9 @@ import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; -/** Cluster implementation. */ public final class ClusterImpl implements Cluster { - private static final Logger LOGGER = System.getLogger(Cluster.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(Cluster.class); private static final Pattern NAMESPACE_PATTERN = Pattern.compile("^(\\w+[\\w\\-./]*\\w)+"); @@ -115,9 +114,7 @@ private void initLifecycle() { .then(doStart()) .doOnSuccess(avoid -> onStart.emitEmpty(busyLooping(Duration.ofSeconds(3)))) .doOnError(th -> onStart.emitError(th, busyLooping(Duration.ofSeconds(3)))) - .subscribe( - null, - th -> LOGGER.log(Level.ERROR, "[{0}][doStart] Exception occurred:", localMember, th)); + .subscribe(null, th -> LOGGER.error("[{}][doStart] Exception occurred:", localMember, th)); shutdown .asMono() @@ -126,11 +123,7 @@ private void initLifecycle() { .subscribe( null, th -> - LOGGER.log( - Level.WARNING, - "[{0}][doShutdown] Exception occurred: {1}", - localMember, - th.toString())); + LOGGER.warn("[{}][doShutdown] Exception occurred: {}", localMember, th.toString())); } /** @@ -293,9 +286,7 @@ private Mono doStart0() { .subscribe( event -> membershipSink.emitNext(event, busyLooping(Duration.ofSeconds(3))), - ex -> - LOGGER.log( - Level.ERROR, "[{0}][membership][error] cause:", localMember, ex), + ex -> LOGGER.error("[{}][membership][error] cause:", localMember, ex), () -> membershipSink.emitComplete(busyLooping(Duration.ofSeconds(3))))); return Mono.fromRunnable(() -> failureDetector.start()) @@ -305,10 +296,8 @@ private Mono doStart0() { .then(membership.start()) .then(); }) - .doOnSubscribe( - s -> - LOGGER.log(Level.INFO, "[{0}][doStart] Starting, config: {1}", localMember, config)) - .doOnSuccess(avoid -> LOGGER.log(Level.INFO, "[{0}][doStart] Started", localMember)) + .doOnSubscribe(s -> LOGGER.info("[{}][doStart] Starting, config: {}", localMember, config)) + .doOnSuccess(avoid -> LOGGER.info("[{}][doStart] Started", localMember)) .thenReturn(this); } @@ -349,19 +338,17 @@ private void startHandler() { listenMessage() .subscribe( handler::onMessage, - ex -> LOGGER.log(Level.ERROR, "[{0}][onMessage][error] cause:", localMember, ex))); + ex -> LOGGER.error("[{}][onMessage][error] cause:", localMember, ex))); actionsDisposables.add( listenMembership() .subscribe( handler::onMembershipEvent, - ex -> - LOGGER.log( - Level.ERROR, "[{0}][onMembershipEvent][error] cause:", localMember, ex))); + ex -> LOGGER.error("[{}][onMembershipEvent][error] cause:", localMember, ex))); actionsDisposables.add( listenGossip() .subscribe( handler::onGossip, - ex -> LOGGER.log(Level.ERROR, "[{0}][onGossip][error] cause:", localMember, ex))); + ex -> LOGGER.error("[{}][onGossip][error] cause:", localMember, ex))); } private Flux listenMessage() { @@ -469,12 +456,11 @@ public void shutdown() { private Mono doShutdown() { return Mono.defer( () -> { - LOGGER.log(Level.INFO, "[{0}][doShutdown] Shutting down", localMember); + LOGGER.info("[{}][doShutdown] Shutting down", localMember); return Flux.concatDelayError(leaveCluster(), dispose(), transport.stop()) .then() .doFinally(s -> scheduler.dispose()) - .doOnSuccess( - avoid -> LOGGER.log(Level.INFO, "[{0}][doShutdown] Shutdown", localMember)); + .doOnSuccess(avoid -> LOGGER.info("[{}][doShutdown] Shutdown", localMember)); }); } @@ -482,16 +468,12 @@ private Mono leaveCluster() { return membership .leaveCluster() .subscribeOn(scheduler) - .doOnSubscribe( - s -> LOGGER.log(Level.INFO, "[{0}][leaveCluster] Leaving cluster", localMember)) - .doOnSuccess(s -> LOGGER.log(Level.INFO, "[{0}][leaveCluster] Left cluster", localMember)) + .doOnSubscribe(s -> LOGGER.info("[{}][leaveCluster] Leaving cluster", localMember)) + .doOnSuccess(s -> LOGGER.info("[{}][leaveCluster] Left cluster", localMember)) .doOnError( ex -> - LOGGER.log( - Level.WARNING, - "[{0}][leaveCluster] Exception occurred: {1}", - localMember, - ex.toString())) + LOGGER.warn( + "[{}][leaveCluster] Exception occurred: {}", localMember, ex.toString())) .then(); } diff --git a/cluster/src/main/java/io/scalecube/cluster/fdetector/FailureDetectorImpl.java b/cluster/src/main/java/io/scalecube/cluster/fdetector/FailureDetectorImpl.java index dc6f3d0f..a76ce4ab 100644 --- a/cluster/src/main/java/io/scalecube/cluster/fdetector/FailureDetectorImpl.java +++ b/cluster/src/main/java/io/scalecube/cluster/fdetector/FailureDetectorImpl.java @@ -8,8 +8,6 @@ import io.scalecube.cluster.membership.MembershipEvent; import io.scalecube.cluster.transport.api.Message; import io.scalecube.cluster.transport.api.Transport; -import java.lang.System.Logger; -import java.lang.System.Logger.Level; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; @@ -19,6 +17,8 @@ import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import reactor.core.Disposable; import reactor.core.Disposables; import reactor.core.publisher.Flux; @@ -27,7 +27,7 @@ public final class FailureDetectorImpl implements FailureDetector { - private static final Logger LOGGER = System.getLogger(FailureDetector.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(FailureDetector.class); // Qualifiers @@ -89,20 +89,15 @@ public FailureDetectorImpl( .subscribe( this::onMessage, ex -> - LOGGER.log( - Level.ERROR, - "[{0}][{1,number,#}][onMessage][error] cause:", - localMember, - currentPeriod, - ex)), + LOGGER.error( + "[{}][{}][onMessage][error] cause:", localMember, currentPeriod, ex)), membershipProcessor // Listen membership events to update remoteMembers .publishOn(scheduler) .subscribe( this::onMembershipEvent, ex -> - LOGGER.log( - Level.ERROR, - "[{0}][{1,number,#}][onMembershipEvent][error] cause:", + LOGGER.error( + "[{}][{}][onMembershipEvent][error] cause:", localMember, currentPeriod, ex)))); @@ -148,8 +143,7 @@ private void doPing() { PingData pingData = new PingData(localMember, pingMember); Message pingMsg = Message.withData(pingData).qualifier(PING).correlationId(cid).build(); - LOGGER.log( - Level.DEBUG, "[{0}][{1,number,#}] Send Ping to {2}", localMember, period, pingMember); + LOGGER.debug("[{}][{}] Send Ping to {}", localMember, period, pingMember); String address = pingMember.address(); transport .requestResponse(address, pingMsg) @@ -157,18 +151,13 @@ private void doPing() { .publishOn(scheduler) .subscribe( message -> { - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Received PingAck from {2}", - localMember, - period, - message.sender()); + LOGGER.debug( + "[{}][{}] Received PingAck from {}", localMember, period, message.sender()); publishPingResult(period, pingMember, computeMemberStatus(message, period)); }, ex -> { - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Failed to get PingAck from {2} within {3} ms", + LOGGER.debug( + "[{}][{}] Failed to get PingAck from {} within {} ms", localMember, period, pingMember, @@ -178,8 +167,7 @@ private void doPing() { final List pingReqMembers = selectPingReqMembers(pingMember); if (timeLeft <= 0 || pingReqMembers.isEmpty()) { - LOGGER.log( - Level.DEBUG, "[{0}][{1,number,#}] No PingReq occurred", localMember, period); + LOGGER.debug("[{}][{}] No PingReq occurred", localMember, period); publishPingResult(period, pingMember, MemberStatus.SUSPECT); } else { doPingReq(currentPeriod, pingMember, pingReqMembers, cid); @@ -194,13 +182,8 @@ private void doPingReq( .qualifier(PING_REQ) .correlationId(cid) .build(); - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Send PingReq to {2} for {3}", - localMember, - period, - pingReqMembers, - pingMember); + LOGGER.debug( + "[{}][{}] Send PingReq to {} for {}", localMember, period, pingReqMembers, pingMember); Duration timeout = Duration.ofMillis(config.pingInterval() - config.pingTimeout()); pingReqMembers.forEach( @@ -211,9 +194,8 @@ private void doPingReq( .publishOn(scheduler) .subscribe( message -> { - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Received transit PingAck from {2} to {3}", + LOGGER.debug( + "[{}][{}] Received transit PingAck from {} to {}", localMember, period, message.sender(), @@ -221,11 +203,10 @@ private void doPingReq( publishPingResult(period, pingMember, computeMemberStatus(message, period)); }, throwable -> { - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] " + LOGGER.debug( + "[{}][{}] " + "Timeout getting transit " - + "PingAck from {2} to {3} within {4,number,#}ms", + + "PingAck from {} to {} within {}ms", localMember, period, member, @@ -253,14 +234,12 @@ private void onMessage(Message message) { private void onPing(Message message) { long period = this.currentPeriod; String sender = message.sender(); - LOGGER.log( - Level.DEBUG, "[{0}][{1,number,#}] Received Ping from {2}", localMember, period, sender); + LOGGER.debug("[{}][{}] Received Ping from {}", localMember, period, sender); PingData data = message.data(); data = data.withAckType(AckType.DEST_OK); if (!data.getTo().id().equals(localMember.id())) { - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Received Ping from {2} to {3}, but local member is {4}", + LOGGER.debug( + "[{}][{}] Received Ping from {} to {}, but local member is {}", localMember, period, sender, @@ -272,16 +251,14 @@ private void onPing(Message message) { Message ackMessage = Message.withData(data).qualifier(PING_ACK).correlationId(correlationId).build(); String address = data.getFrom().address(); - LOGGER.log( - Level.DEBUG, "[{0}][{1,number,#}] Send PingAck to {2}", localMember, period, address); + LOGGER.debug("[{}][{}] Send PingAck to {}", localMember, period, address); transport .send(address, ackMessage) .subscribe( null, ex -> - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Failed to send PingAck to {2}, cause: {3}", + LOGGER.debug( + "[{}][{}] Failed to send PingAck to {}, cause: {}", localMember, period, address, @@ -291,12 +268,7 @@ private void onPing(Message message) { /** Listens to PING_REQ message and sends PING to requested cluster member. */ private void onPingReq(Message message) { long period = this.currentPeriod; - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Received PingReq from {2}", - localMember, - period, - message.sender()); + LOGGER.debug("[{}][{}] Received PingReq from {}", localMember, period, message.sender()); PingData data = message.data(); Member target = data.getTo(); Member originalIssuer = data.getFrom(); @@ -305,16 +277,14 @@ private void onPingReq(Message message) { Message pingMessage = Message.withData(pingReqData).qualifier(PING).correlationId(correlationId).build(); String address = target.address(); - LOGGER.log( - Level.DEBUG, "[{0}][{1,number,#}] Send transit Ping to {2}", localMember, period, address); + LOGGER.debug("[{}][{}] Send transit Ping to {}", localMember, period, address); transport .send(address, pingMessage) .subscribe( null, ex -> - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Failed to send transit Ping to {2}, cause: {3}", + LOGGER.debug( + "[{}][{}] Failed to send transit Ping to {}, cause: {}", localMember, period, address, @@ -327,12 +297,8 @@ private void onPingReq(Message message) { */ private void onTransitPingAck(Message message) { long period = this.currentPeriod; - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Received transit PingAck from {2}", - localMember, - period, - message.sender()); + LOGGER.debug( + "[{}][{}] Received transit PingAck from {}", localMember, period, message.sender()); PingData data = message.data(); AckType ackType = data.getAckType(); Member target = data.getOriginalIssuer(); @@ -341,20 +307,14 @@ private void onTransitPingAck(Message message) { Message originalAckMessage = Message.withData(originalAckData).qualifier(PING_ACK).correlationId(correlationId).build(); String address = target.address(); - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Resend transit PingAck to {2}", - localMember, - period, - address); + LOGGER.debug("[{}][{}] Resend transit PingAck to {}", localMember, period, address); transport .send(address, originalAckMessage) .subscribe( null, ex -> - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Failed to resend transit PingAck to {2}, cause: {3}", + LOGGER.debug( + "[{}][{}] Failed to resend transit PingAck to {}, cause: {}", localMember, period, address, @@ -366,9 +326,8 @@ private void onMembershipEvent(MembershipEvent event) { if (event.isRemoved()) { boolean removed = pingMembers.remove(member); if (removed) { - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Removed {2} from pingMembers list (size={3})", + LOGGER.debug( + "[{}][{}] Removed {} from pingMembers list (size={})", localMember, currentPeriod, member, @@ -380,9 +339,8 @@ private void onMembershipEvent(MembershipEvent event) { int size = pingMembers.size(); int index = size > 0 ? ThreadLocalRandom.current().nextInt(size) : 0; pingMembers.add(index, member); - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Added {2} to pingMembers list (size={3})", + LOGGER.debug( + "[{}][{}] Added {} to pingMembers list (size={})", localMember, currentPeriod, member, @@ -420,13 +378,7 @@ private List selectPingReqMembers(Member pingMember) { } private void publishPingResult(long period, Member member, MemberStatus status) { - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Member {2} detected as {3}", - localMember, - period, - member, - status); + LOGGER.debug("[{}][{}] Member {} detected as {}", localMember, period, member, status); sink.emitNext(new FailureDetectorEvent(member, status), busyLooping(Duration.ofSeconds(3))); } @@ -447,12 +399,7 @@ private MemberStatus computeMemberStatus(Message message, long period) { memberStatus = MemberStatus.DEAD; break; default: - LOGGER.log( - Level.WARNING, - "[{0}][{1,number,#}] Unknown PingData.AckType received: {2}", - localMember, - period, - ackType); + LOGGER.warn("[{}][{}] Unknown PingData.AckType received: {}", localMember, period, ackType); memberStatus = MemberStatus.SUSPECT; } return memberStatus; diff --git a/cluster/src/main/java/io/scalecube/cluster/gossip/GossipProtocolImpl.java b/cluster/src/main/java/io/scalecube/cluster/gossip/GossipProtocolImpl.java index 66746cfd..e51d441f 100644 --- a/cluster/src/main/java/io/scalecube/cluster/gossip/GossipProtocolImpl.java +++ b/cluster/src/main/java/io/scalecube/cluster/gossip/GossipProtocolImpl.java @@ -7,8 +7,6 @@ import io.scalecube.cluster.membership.MembershipEvent; import io.scalecube.cluster.transport.api.Message; import io.scalecube.cluster.transport.api.Transport; -import java.lang.System.Logger; -import java.lang.System.Logger.Level; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; @@ -21,6 +19,8 @@ import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import reactor.core.Disposable; import reactor.core.Disposables; import reactor.core.publisher.Flux; @@ -31,7 +31,7 @@ public final class GossipProtocolImpl implements GossipProtocol { - private static final Logger LOGGER = System.getLogger(GossipProtocol.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(GossipProtocol.class); // Qualifiers @@ -94,24 +94,14 @@ public GossipProtocolImpl( .publishOn(scheduler) .subscribe( this::onMembershipEvent, - ex -> - LOGGER.log( - Level.ERROR, - "[{0}][onMembershipEvent][error] cause:", - localMember, - ex)), + ex -> LOGGER.error("[{}][onMembershipEvent][error] cause:", localMember, ex)), transport .listen() // Listen gossip requests .publishOn(scheduler) .filter(this::isGossipRequest) .subscribe( this::onGossipRequest, - ex -> - LOGGER.log( - Level.ERROR, - "[{0}][onGossipRequest][error] cause:", - localMember, - ex)))); + ex -> LOGGER.error("[{}][onGossipRequest][error] cause:", localMember, ex)))); } @Override @@ -168,12 +158,7 @@ private void doSpreadGossip() { // Sweep gossips Set gossipsToRemove = getGossipsToRemove(period); if (!gossipsToRemove.isEmpty()) { - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Sweep gossips: {2}", - localMember, - period, - gossipsToRemove); + LOGGER.debug("[{}][{}] Sweep gossips: {}", localMember, period, gossipsToRemove); for (String gossipId : gossipsToRemove) { gossips.remove(gossipId); } @@ -182,9 +167,8 @@ private void doSpreadGossip() { // Check spread gossips Set gossipsThatSpread = getGossipsThatMostLikelyDisseminated(period); if (!gossipsThatSpread.isEmpty()) { - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Most likely disseminated gossips: {2}", + LOGGER.debug( + "[{}][{}] Most likely disseminated gossips: {}", localMember, period, gossipsThatSpread); @@ -196,12 +180,7 @@ private void doSpreadGossip() { } } } catch (Exception ex) { - LOGGER.log( - Level.WARNING, - "[{0}][{1,number,#}][doSpreadGossip] Exception occurred:", - localMember, - period, - ex); + LOGGER.warn("[{}][{}][doSpreadGossip] Exception occurred:", localMember, period, ex); } } @@ -246,10 +225,9 @@ private void checkGossipSegmentation() { // or network issue final SequenceIdCollector sequenceIdCollector = entry.getValue(); if (sequenceIdCollector.size() > intervalsThreshold) { - LOGGER.log( - Level.WARNING, - "[{0}][{1,number,#}] Too many missed gossip messages from original gossiper: {2}, " - + "current node({3}) was SUSPECTED much for a long time or connection problem", + LOGGER.warn( + "[{}][{}] Too many missed gossip messages from original gossiper: {}, " + + "current node({}) was SUSPECTED much for a long time or connection problem", localMember, currentPeriod, entry.getKey(), @@ -266,9 +244,8 @@ private void onMembershipEvent(MembershipEvent event) { boolean removed = remoteMembers.remove(member); sequenceIdCollectors.remove(member.id()); if (removed) { - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Removed {2} from remoteMembers list (size={3,number,#})", + LOGGER.debug( + "[{}][{}] Removed {} from remoteMembers list (size={})", localMember, currentPeriod, member, @@ -277,9 +254,8 @@ private void onMembershipEvent(MembershipEvent event) { } if (event.isAdded()) { remoteMembers.add(member); - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] Added {2} to remoteMembers list (size={3,number,#})", + LOGGER.debug( + "[{}][{}] Added {} to remoteMembers list (size={})", localMember, currentPeriod, member, @@ -322,10 +298,8 @@ private void spreadGossipsTo(long period, Member member) { .subscribe( null, ex -> - LOGGER.log( - Level.DEBUG, - "[{0}][{1,number,#}] " - + "Failed to send GossipReq({2}) to {3}, cause: {4}", + LOGGER.debug( + "[{}][{}] Failed to send GossipReq({}) to {}, cause: {}", localMember, period, message, diff --git a/cluster/src/main/java/io/scalecube/cluster/membership/MembershipProtocolImpl.java b/cluster/src/main/java/io/scalecube/cluster/membership/MembershipProtocolImpl.java index 7ecf5067..011190c8 100644 --- a/cluster/src/main/java/io/scalecube/cluster/membership/MembershipProtocolImpl.java +++ b/cluster/src/main/java/io/scalecube/cluster/membership/MembershipProtocolImpl.java @@ -16,8 +16,6 @@ import io.scalecube.cluster.metadata.MetadataStore; import io.scalecube.cluster.transport.api.Message; import io.scalecube.cluster.transport.api.Transport; -import java.lang.System.Logger; -import java.lang.System.Logger.Level; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; @@ -41,6 +39,8 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import reactor.core.Disposable; import reactor.core.Disposables; import reactor.core.publisher.Flux; @@ -52,7 +52,7 @@ @SuppressWarnings({"FieldCanBeLocal", "unused"}) public final class MembershipProtocolImpl implements MembershipProtocol { - private static final Logger LOGGER = System.getLogger(MembershipProtocol.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(MembershipProtocol.class); private enum MembershipUpdateReason { FAILURE_DETECTOR_EVENT, @@ -142,30 +142,22 @@ public MembershipProtocolImpl( .publishOn(scheduler) .subscribe( this::onMessage, - ex -> - LOGGER.log(Level.ERROR, "[{0}][onMessage][error] cause:", localMember, ex)), + ex -> LOGGER.error("[{}][onMessage][error] cause:", localMember, ex)), failureDetector .listen() // Listen to events from failure detector .publishOn(scheduler) .subscribe( this::onFailureDetectorEvent, ex -> - LOGGER.log( - Level.ERROR, - "[{0}][onFailureDetectorEvent][error] cause:", - localMember, - ex)), + LOGGER.error( + "[{}][onFailureDetectorEvent][error] cause:", localMember, ex)), gossipProtocol .listen() // Listen to membership gossips .publishOn(scheduler) .subscribe( this::onMembershipGossip, ex -> - LOGGER.log( - Level.DEBUG, - "[{0}][onMembershipGossip][error] cause:", - localMember, - ex)))); + LOGGER.debug("[{}][onMembershipGossip][error] cause:", localMember, ex)))); } // Remove duplicates and local address(es) @@ -205,7 +197,7 @@ private boolean checkAddressesNotEqual(String address0, String address1) { if (!address0.equals(address1)) { return true; } else { - LOGGER.log(Level.WARNING, "[{0}] Filtering out seed address: {1}", localMember, address0); + LOGGER.warn("[{}] Filtering out seed address: {}", localMember, address0); return false; } } @@ -264,8 +256,7 @@ private void start0(MonoSink sink) { return; } // If seed addresses are specified in config - send initial sync to those nodes - LOGGER.log( - Level.INFO, "[{0}] Making initial Sync to all seed members: {1}", localMember, seedMembers); + LOGGER.info("[{}] Making initial Sync to all seed members: {}", localMember, seedMembers); //noinspection unchecked Mono[] syncs = @@ -277,9 +268,8 @@ private void start0(MonoSink sink) { address, prepareSyncDataMsg(SYNC, UUID.randomUUID().toString())) .doOnError( ex -> - LOGGER.log( - Level.WARNING, - "[{0}] Exception on initial Sync, cause: {1}", + LOGGER.warn( + "[{}] Exception on initial Sync, cause: {}", localMember, ex.toString())) .onErrorResume(Exception.class, e -> Mono.empty())) @@ -299,11 +289,8 @@ address, prepareSyncDataMsg(SYNC, UUID.randomUUID().toString())) .subscribe( null, ex -> - LOGGER.log( - Level.WARNING, - "[{0}] Exception on initial SyncAck, cause: {1}", - localMember, - ex.toString())); + LOGGER.warn( + "[{}] Exception on initial SyncAck, cause: {}", localMember, ex.toString())); } @Override @@ -359,15 +346,14 @@ private void doSync() { } Message message = prepareSyncDataMsg(SYNC, null); - LOGGER.log(Level.DEBUG, "[{0}][doSync] Send Sync to {1}", localMember, address); + LOGGER.debug("[{}][doSync] Send Sync to {}", localMember, address); transport .send(address, message) .subscribe( null, ex -> - LOGGER.log( - Level.DEBUG, - "[{0}][doSync] Failed to send Sync to {1}, cause: {2}", + LOGGER.debug( + "[{}][doSync] Failed to send Sync to {}, cause: {}", localMember, address, ex.toString())); @@ -380,14 +366,11 @@ private void doSync() { private void onMessage(Message message) { if (isSync(message)) { onSync(message) - .subscribe( - null, ex -> LOGGER.log(Level.ERROR, "[{0}][onSync][error] cause:", localMember, ex)); + .subscribe(null, ex -> LOGGER.error("[{}][onSync][error] cause:", localMember, ex)); } else if (isSyncAck(message)) { if (message.correlationId() == null) { // filter out initial sync onSyncAck(message, false) - .subscribe( - null, - ex -> LOGGER.log(Level.ERROR, "[{0}][onSyncAck][error] cause:", localMember, ex)); + .subscribe(null, ex -> LOGGER.error("[{}][onSyncAck][error] cause:", localMember, ex)); } } } @@ -407,8 +390,7 @@ private boolean isSyncAck(Message message) { private Mono onSyncAck(Message syncAckMsg, boolean onStart) { return Mono.defer( () -> { - LOGGER.log( - Level.DEBUG, "[{0}] Received SyncAck from {1}", localMember, syncAckMsg.sender()); + LOGGER.debug("[{}] Received SyncAck from {}", localMember, syncAckMsg.sender()); return syncMembership(syncAckMsg.data(), onStart); }); } @@ -418,7 +400,7 @@ private Mono onSync(Message syncMsg) { return Mono.defer( () -> { final String sender = syncMsg.sender(); - LOGGER.log(Level.DEBUG, "[{0}] Received Sync from {1}", localMember, sender); + LOGGER.debug("[{}] Received Sync from {}", localMember, sender); return syncMembership(syncMsg.data(), false) .doOnSuccess( avoid -> { @@ -428,9 +410,8 @@ private Mono onSync(Message syncMsg) { .subscribe( null, ex -> - LOGGER.log( - Level.DEBUG, - "[{0}] Failed to send SyncAck to {}, cause: {1}", + LOGGER.debug( + "[{}] Failed to send SyncAck to {}, cause: {}", localMember, sender, ex.toString())); @@ -447,11 +428,7 @@ private void onFailureDetectorEvent(FailureDetectorEvent fdEvent) { if (r0.status() == fdEvent.status()) { // status not changed return; } - LOGGER.log( - Level.DEBUG, - "[{0}][onFailureDetectorEvent] Received status change: {1}", - localMember, - fdEvent); + LOGGER.debug("[{}][onFailureDetectorEvent] Received status change: {}", localMember, fdEvent); if (fdEvent.status() == ALIVE) { // TODO: Consider to make more elegant solution // Alive won't override SUSPECT so issue instead extra sync with member to force it spread @@ -463,9 +440,8 @@ private void onFailureDetectorEvent(FailureDetectorEvent fdEvent) { .subscribe( null, ex -> - LOGGER.log( - Level.DEBUG, - "[{0}][onFailureDetectorEvent] Failed to send Sync to {1}, cause: {2}", + LOGGER.debug( + "[{}][onFailureDetectorEvent] Failed to send Sync to {}, cause: {}", localMember, address, ex.toString())); @@ -476,9 +452,8 @@ private void onFailureDetectorEvent(FailureDetectorEvent fdEvent) { .subscribe( null, ex -> - LOGGER.log( - Level.ERROR, - "[{0}][onFailureDetectorEvent][updateMembership][error] cause:", + LOGGER.error( + "[{}][onFailureDetectorEvent][updateMembership][error] cause:", localMember, ex)); } @@ -488,16 +463,13 @@ private void onFailureDetectorEvent(FailureDetectorEvent fdEvent) { private void onMembershipGossip(Message message) { if (MEMBERSHIP_GOSSIP.equals(message.qualifier())) { MembershipRecord record = message.data(); - LOGGER.log(Level.DEBUG, "[{0}] Received membership gossip: {1}", localMember, record); + LOGGER.debug("[{}] Received membership gossip: {}", localMember, record); updateMembership(record, MembershipUpdateReason.MEMBERSHIP_GOSSIP) .subscribe( null, ex -> - LOGGER.log( - Level.ERROR, - "[{0}][onMembershipGossip][updateMembership][error] cause:", - localMember, - ex)); + LOGGER.error( + "[{}][onMembershipGossip][updateMembership][error] cause:", localMember, ex)); } } @@ -545,9 +517,8 @@ private Mono syncMembership(SyncData syncData, boolean onStart) { updateMembership(r1, reason) .doOnError( ex -> - LOGGER.log( - Level.WARNING, - "[{0}][syncMembership][{1}][error] cause: {2}", + LOGGER.warn( + "[{}][syncMembership][{}][error] cause: {}", localMember, reason, ex.toString())) @@ -600,10 +571,9 @@ private Mono updateMembership(MembershipRecord r1, MembershipUpdateReason String localNamespace = membershipConfig.namespace(); String namespace = r1.member().namespace(); if (!areNamespacesRelated(localNamespace, namespace)) { - LOGGER.log( - Level.DEBUG, - "[{0}][updateMembership][{1}] Skipping update, " - + "namespace not matched, local: {2}, inbound: {3}", + LOGGER.debug( + "[{}][updateMembership][{}] Skipping update, " + + "namespace not matched, local: {}, inbound: {}", localMember, reason, localNamespace, @@ -617,10 +587,9 @@ private Mono updateMembership(MembershipRecord r1, MembershipUpdateReason // if current record is LEAVING then we want to process other event too // Check if new record r1 overrides existing membership record r0 if ((r0 == null || !r0.isLeaving()) && !r1.isOverrides(r0)) { - LOGGER.log( - Level.DEBUG, - "[{0}][updateMembership][{1}] Skipping update, " - + "can't override r0: {2} with received r1: {3}", + LOGGER.debug( + "[{}][updateMembership][{}] Skipping update, " + + "can't override r0: {} with received r1: {}", localMember, reason, r0, @@ -665,10 +634,9 @@ private Mono updateMembership(MembershipRecord r1, MembershipUpdateReason .fetchMetadata(r1.member()) .doOnError( ex -> - LOGGER.log( - Level.WARNING, - "[{0}][updateMembership][{1}] Skipping to add/update member: {2}, " - + "due to failed fetchMetadata call (cause: {3})", + LOGGER.warn( + "[{}][updateMembership][{}] Skipping to add/update member: {}, " + + "due to failed fetchMetadata call (cause: {})", localMember, reason, r1, @@ -721,11 +689,10 @@ private Mono onSelfMemberDetected( membershipTable.put(localMember.id(), r2); - LOGGER.log( - Level.DEBUG, - "[{0}][updateMembership][{1}] Updating incarnation, " - + "local record r0: {2} to received r1: {3}, " - + "spreading with increased incarnation r2: {4}", + LOGGER.debug( + "[{}][updateMembership][{}] Updating incarnation, " + + "local record r0: {} to received r1: {}, " + + "spreading with increased incarnation r2: {}", localMember, reason, r0, @@ -767,7 +734,7 @@ private Mono onLeavingDetected(MembershipRecord r0, MembershipRecord r1) { } private void publishEvent(MembershipEvent event) { - LOGGER.log(Level.INFO, "[{0}][publishEvent] {1}", localMember, event); + LOGGER.info("[{}][publishEvent] {}", localMember, event); sink.emitNext(event, busyLooping(Duration.ofSeconds(3))); } @@ -790,10 +757,9 @@ private Mono onDeadMemberDetected(MembershipRecord r1) { // Log that member left gracefully or without notification if (r0.isLeaving()) { - LOGGER.log(Level.INFO, "[{0}] Member left gracefully: {1}", localMember, member); + LOGGER.info("[{}] Member left gracefully: {}", localMember, member); } else { - LOGGER.log( - Level.INFO, "[{0}] Member left without notification: {1}", localMember, member); + LOGGER.info("[{}] Member left without notification: {}", localMember, member); } final long timestamp = System.currentTimeMillis(); @@ -832,8 +798,7 @@ private void onAliveMemberDetected( private void cancelSuspicionTimeoutTask(String memberId) { Disposable future = suspicionTimeoutTasks.remove(memberId); if (future != null && !future.isDisposed()) { - LOGGER.log( - Level.DEBUG, "[{0}] Cancelled SuspicionTimeoutTask for {1}", localMember, memberId); + LOGGER.debug("[{}] Cancelled SuspicionTimeoutTask for {}", localMember, memberId); future.dispose(); } } @@ -848,9 +813,8 @@ private void scheduleSuspicionTimeoutTask(MembershipRecord r) { suspicionTimeoutTasks.computeIfAbsent( r.member().id(), id -> { - LOGGER.log( - Level.DEBUG, - "[{0}] Scheduled SuspicionTimeoutTask for {1}, suspicionTimeout: {2,number,#}ms", + LOGGER.debug( + "[{}] Scheduled SuspicionTimeoutTask for {}, suspicionTimeout: {}ms", localMember, id, suspicionTimeout); @@ -863,18 +827,14 @@ private void onSuspicionTimeout(String memberId) { suspicionTimeoutTasks.remove(memberId); MembershipRecord r = membershipTable.get(memberId); if (r != null) { - LOGGER.log( - Level.DEBUG, "[{0}] Declare SUSPECTED member {1} as DEAD by timeout", localMember, r); + LOGGER.debug("[{}] Declare SUSPECTED member {} as DEAD by timeout", localMember, r); MembershipRecord deadRecord = new MembershipRecord(r.member(), DEAD, r.incarnation()); updateMembership(deadRecord, MembershipUpdateReason.SUSPICION_TIMEOUT) .subscribe( null, ex -> - LOGGER.log( - Level.ERROR, - "[{0}][onSuspicionTimeout][updateMembership][error] cause:", - localMember, - ex)); + LOGGER.error( + "[{}][onSuspicionTimeout][updateMembership][error] cause:", localMember, ex)); } } @@ -896,14 +856,13 @@ private Mono spreadMembershipGossip(MembershipRecord r) { return Mono.defer( () -> { Message msg = Message.withData(r).qualifier(MEMBERSHIP_GOSSIP).build(); - LOGGER.log(Level.DEBUG, "[{0}] Send membership with gossip", localMember); + LOGGER.debug("[{}] Send membership with gossip", localMember); return gossipProtocol .spread(msg) .doOnError( ex -> - LOGGER.log( - Level.DEBUG, - "[{0}] Failed to send membership with gossip, cause: {1}", + LOGGER.debug( + "[{}] Failed to send membership with gossip, cause: {}", localMember, ex.toString())) .then(); diff --git a/cluster/src/main/java/io/scalecube/cluster/metadata/MetadataStoreImpl.java b/cluster/src/main/java/io/scalecube/cluster/metadata/MetadataStoreImpl.java index c5710d6a..35caa671 100644 --- a/cluster/src/main/java/io/scalecube/cluster/metadata/MetadataStoreImpl.java +++ b/cluster/src/main/java/io/scalecube/cluster/metadata/MetadataStoreImpl.java @@ -4,8 +4,6 @@ import io.scalecube.cluster.Member; import io.scalecube.cluster.transport.api.Message; import io.scalecube.cluster.transport.api.Transport; -import java.lang.System.Logger; -import java.lang.System.Logger.Level; import java.nio.ByteBuffer; import java.time.Duration; import java.util.HashMap; @@ -13,6 +11,8 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import reactor.core.Disposable; import reactor.core.Disposables; import reactor.core.publisher.Mono; @@ -20,7 +20,7 @@ public class MetadataStoreImpl implements MetadataStore { - private static final Logger LOGGER = System.getLogger(MetadataStore.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(MetadataStore.class); // Qualifiers @@ -80,7 +80,7 @@ public void start() { .publishOn(scheduler) .subscribe( this::onMessage, - ex -> LOGGER.log(Level.ERROR, "[{0}][onMessage][error] cause:", localMember, ex))); + ex -> LOGGER.error("[{}][onMessage][error] cause:", localMember, ex))); } @Override @@ -115,19 +115,11 @@ public ByteBuffer updateMetadata(Member member, ByteBuffer metadata) { ByteBuffer result = membersMetadata.put(member, value); if (result == null) { - LOGGER.log( - Level.DEBUG, - "[{0}] Added metadata(size={1,number,#}) for member {2}", - localMember, - value.remaining(), - member); + LOGGER.debug( + "[{}] Added metadata(size={}) for member {}", localMember, value.remaining(), member); } else { - LOGGER.log( - Level.DEBUG, - "[{0}] Updated metadata(size={1,number,#}) for member {2}", - localMember, - value.remaining(), - member); + LOGGER.debug( + "[{}] Updated metadata(size={}) for member {}", localMember, value.remaining(), member); } return result; } @@ -140,9 +132,8 @@ public ByteBuffer removeMetadata(Member member) { // remove ByteBuffer metadata = membersMetadata.remove(member); if (metadata != null) { - LOGGER.log( - Level.DEBUG, - "[{0}] Removed metadata(size={1,number,#}) for member {2}", + LOGGER.debug( + "[{}] Removed metadata(size={}) for member {}", localMember, metadata.remaining(), member); @@ -158,8 +149,7 @@ public Mono fetchMetadata(Member member) { final String cid = UUID.randomUUID().toString(); final String targetAddress = member.address(); - LOGGER.log( - Level.DEBUG, "[{0}][{1}] Getting metadata for member {2}", localMember, cid, member); + LOGGER.debug("[{}][{}] Getting metadata for member {}", localMember, cid, member); Message request = Message.builder() @@ -174,9 +164,8 @@ public Mono fetchMetadata(Member member) { .publishOn(scheduler) .doOnSuccess( s -> - LOGGER.log( - Level.DEBUG, - "[{0}][{1}] Received GetMetadataResp from {2}", + LOGGER.debug( + "[{}][{}] Received GetMetadataResp from {}", localMember, cid, targetAddress)) @@ -184,10 +173,9 @@ public Mono fetchMetadata(Member member) { .map(GetMetadataResponse::getMetadata) .doOnError( th -> - LOGGER.log( - Level.WARNING, - "[{0}][{1}] Timeout getting GetMetadataResp " - + "from {2} within {3,number,#}ms, cause: {4}", + LOGGER.warn( + "[{}][{}] Timeout getting GetMetadataResp " + + "from {} within {}ms, cause: {}", localMember, cid, targetAddress, @@ -208,16 +196,15 @@ private void onMessage(Message message) { private void onMetadataRequest(Message message) { final String sender = message.sender(); - LOGGER.log(Level.DEBUG, "[{0}] Received GetMetadataReq from {1}", localMember, sender); + LOGGER.debug("[{}] Received GetMetadataReq from {}", localMember, sender); GetMetadataRequest reqData = message.data(); Member targetMember = reqData.getMember(); // Validate target member if (!targetMember.id().equals(localMember.id())) { - LOGGER.log( - Level.WARNING, - "[{0}] Received GetMetadataReq from {1} to {2}, but local member is {3}", + LOGGER.warn( + "[{}] Received GetMetadataReq from {} to {}, but local member is {}", localMember, sender, targetMember, @@ -235,15 +222,14 @@ private void onMetadataRequest(Message message) { .data(respData) .build(); - LOGGER.log(Level.DEBUG, "[{0}] Send GetMetadataResp to {1}", localMember, sender); + LOGGER.debug("[{}] Send GetMetadataResp to {}", localMember, sender); transport .send(sender, response) .subscribe( null, ex -> - LOGGER.log( - Level.DEBUG, - "[{0}] Failed to send GetMetadataResp to {1}, cause: {2}", + LOGGER.debug( + "[{}] Failed to send GetMetadataResp to {}, cause: {}", localMember, sender, ex.toString())); @@ -254,9 +240,8 @@ private ByteBuffer encodeMetadata() { try { result = config.metadataCodec().serialize(localMetadata); } catch (Exception e) { - LOGGER.log( - Level.ERROR, - "[{0}] Failed to encode metadata: {1}, cause: {2}", + LOGGER.error( + "[{}] Failed to encode metadata: {}, cause: {}", localMember, localMetadata, e.toString()); diff --git a/cluster/src/test/java/io/scalecube/cluster/BaseTest.java b/cluster/src/test/java/io/scalecube/cluster/BaseTest.java index 2a786007..e4814233 100644 --- a/cluster/src/test/java/io/scalecube/cluster/BaseTest.java +++ b/cluster/src/test/java/io/scalecube/cluster/BaseTest.java @@ -6,30 +6,16 @@ import io.scalecube.cluster.transport.api.TransportConfig; import io.scalecube.cluster.utils.NetworkEmulatorTransport; import io.scalecube.transport.netty.tcp.TcpTransportFactory; -import java.lang.System.Logger; -import java.lang.System.Logger.Level; import java.lang.reflect.Field; import java.time.Duration; import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.TestInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import reactor.core.Exceptions; -/** Base test class. */ public class BaseTest { - protected static final Logger LOGGER = System.getLogger(BaseTest.class.getName()); - - @BeforeEach - public final void baseSetUp(TestInfo testInfo) { - LOGGER.log(Level.INFO, "***** Test started : " + testInfo.getDisplayName() + " *****"); - } - - @AfterEach - public final void baseTearDown(TestInfo testInfo) { - LOGGER.log(Level.INFO, "***** Test finished : " + testInfo.getDisplayName() + " *****"); - } + public static final Logger LOGGER = LoggerFactory.getLogger(BaseTest.class); public static T getField(Object obj, String fieldName) { try { diff --git a/cluster/src/test/java/io/scalecube/cluster/ClusterTest.java b/cluster/src/test/java/io/scalecube/cluster/ClusterTest.java index 9c4068a0..f8ac8eda 100644 --- a/cluster/src/test/java/io/scalecube/cluster/ClusterTest.java +++ b/cluster/src/test/java/io/scalecube/cluster/ClusterTest.java @@ -10,7 +10,6 @@ import io.scalecube.cluster.membership.MembershipEvent.Type; import io.scalecube.cluster.metadata.MetadataCodec; import io.scalecube.transport.netty.tcp.TcpTransportFactory; -import java.lang.System.Logger.Level; import java.net.InetAddress; import java.net.UnknownHostException; import java.time.Duration; @@ -179,9 +178,9 @@ public void testJoinDynamicPort() { .transportFactory(TcpTransportFactory::new) .startAwait()); } - LOGGER.log(Level.INFO, "Start up time: {0} ms", System.currentTimeMillis() - startAt); + LOGGER.info("Start up time: {} ms", System.currentTimeMillis() - startAt); assertEquals(membersNum + 1, seedNode.members().size()); - LOGGER.log(Level.INFO, "Cluster nodes: {0}", seedNode.members()); + LOGGER.info("Cluster nodes: {}", seedNode.members()); } finally { // Shutdown all nodes shutdown( @@ -223,8 +222,7 @@ public void testUpdateMetadata() throws Exception { @Override public void onMembershipEvent(MembershipEvent event) { if (event.isUpdated()) { - LOGGER.log( - Level.INFO, "Received membership update event: {0}", event); + LOGGER.info("Received membership update event: {}", event); updateLatch.countDown(); } } @@ -297,8 +295,7 @@ public void testUpdateMetadataProperty() throws Exception { @Override public void onMembershipEvent(MembershipEvent event) { if (event.isUpdated()) { - LOGGER.log( - Level.INFO, "Received membership update event: {0}", event); + LOGGER.info("Received membership update event: {}", event); updateLatch.countDown(); } } @@ -376,8 +373,7 @@ public void testRemoveMetadataProperty() throws Exception { @Override public void onMembershipEvent(MembershipEvent event) { if (event.isUpdated()) { - LOGGER.log( - Level.INFO, "Received membership update event: {0}", event); + LOGGER.info("Received membership update event: {}", event); updateLatch.countDown(); } } @@ -607,7 +603,7 @@ private void shutdown(List nodes) { .collect(Collectors.toList())) .block(TIMEOUT); } catch (Exception ex) { - LOGGER.log(Level.ERROR, "Exception on cluster shutdown", ex); + LOGGER.error("Exception on cluster shutdown", ex); } } } diff --git a/cluster/src/test/java/io/scalecube/cluster/gossip/GossipProtocolTest.java b/cluster/src/test/java/io/scalecube/cluster/gossip/GossipProtocolTest.java index 444fa910..9842c07c 100644 --- a/cluster/src/test/java/io/scalecube/cluster/gossip/GossipProtocolTest.java +++ b/cluster/src/test/java/io/scalecube/cluster/gossip/GossipProtocolTest.java @@ -16,8 +16,6 @@ import io.scalecube.cluster.transport.api.Message; import io.scalecube.cluster.transport.api.Transport; import io.scalecube.cluster.utils.NetworkEmulatorTransport; -import java.lang.System.Logger; -import java.lang.System.Logger.Level; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; @@ -35,6 +33,8 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; @@ -42,7 +42,7 @@ class GossipProtocolTest extends BaseTest { - private static final Logger LOGGER = System.getLogger(GossipProtocolTest.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(GossipProtocolTest.class); private static final List experiments = Arrays.asList( @@ -138,8 +138,7 @@ void testGossipProtocol(int membersNum, int lossPercent, int meanDelay) throws E if (firstTimeAdded) { latch.countDown(); } else { - LOGGER.log( - Level.ERROR, "Delivered gossip twice to: {0}", transport.address()); + LOGGER.error("Delivered gossip twice to: {}", transport.address()); doubleDelivery.set(true); } } @@ -177,16 +176,10 @@ void testGossipProtocol(int membersNum, int lossPercent, int meanDelay) throws E assertFalse(doubleDelivery.get(), "Delivered gossip twice to same member"); } finally { // Print theoretical results - LOGGER.log( - Level.INFO, + LOGGER.info( "Experiment params: " - + "N={0}, Gfanout={1}, Grepeat_mult={2}, Tgossip={3}ms Ploss={4}%, Tmean={5}ms", - membersNum, - gossipFanout, - gossipRepeatMultiplier, - gossipInterval, - lossPercent, - meanDelay); + + "N={}, Gfanout={}, Grepeat_mult={}, Tgossip={}ms Ploss={}%, Tmean={}ms", + membersNum, gossipFanout, gossipRepeatMultiplier, gossipInterval, lossPercent, meanDelay); double convergProb = gossipConvergencePercent(gossipFanout, gossipRepeatMultiplier, membersNum, lossPercent); long expDissemTime = @@ -194,28 +187,21 @@ void testGossipProtocol(int membersNum, int lossPercent, int meanDelay) throws E int maxMsgPerNode = maxMessagesPerGossipPerNode(gossipFanout, gossipRepeatMultiplier, membersNum); int maxMsgTotal = maxMessagesPerGossipTotal(gossipFanout, gossipRepeatMultiplier, membersNum); - LOGGER.log( - Level.INFO, - "Expected dissemination time is {0}ms with probability {1}%", - expDissemTime, - convergProb); - LOGGER.log( - Level.INFO, "Max messages sent per node {0} and total {1}", maxMsgPerNode, maxMsgTotal); + LOGGER.info( + "Expected dissemination time is {}ms with probability {}%", expDissemTime, convergProb); + LOGGER.info("Max messages sent per node {} and total {}", maxMsgPerNode, maxMsgTotal); // Print actual results - LOGGER.log( - Level.INFO, - "Actual dissemination time: {0}ms (timeout {1}ms)", - disseminationTime, - gossipTimeout); - LOGGER.log(Level.INFO, "Messages sent stats (diss.): {0}", messageSentStatsDissemination); + LOGGER.info( + "Actual dissemination time: {}ms (timeout {}ms)", disseminationTime, gossipTimeout); + LOGGER.info("Messages sent stats (diss.): {}", messageSentStatsDissemination); if (lossPercent > 0) { - LOGGER.log(Level.INFO, "Messages lost stats (diss.): {0}", messageLostStatsDissemination); + LOGGER.info("Messages lost stats (diss.): {}", messageLostStatsDissemination); } if (awaitFullCompletion) { - LOGGER.log(Level.INFO, "Messages sent stats (total): {0}", messageSentStatsOverall); + LOGGER.info("Messages sent stats (total): {}", messageSentStatsOverall); if (lossPercent > 0) { - LOGGER.log(Level.INFO, "Messages lost stats (total): {0}", messageLostStatsOverall); + LOGGER.info("Messages lost stats (total): {}", messageLostStatsOverall); } } @@ -303,7 +289,7 @@ private static void destroyGossipProtocols(List gossipProtoc try { Mono.when(futures).block(Duration.ofSeconds(30)); } catch (Exception ex) { - LOGGER.log(Level.WARNING, "Failed to await transport termination: " + ex); + LOGGER.warn("Failed to await transport termination: " + ex); } // Await a bit diff --git a/codec-parent/pom.xml b/codec-parent/pom.xml index 3e465172..b83bec70 100644 --- a/codec-parent/pom.xml +++ b/codec-parent/pom.xml @@ -1,5 +1,7 @@ - + scalecube-cluster-parent @@ -28,6 +30,13 @@ scalecube-cluster-api ${project.version} + + + ${project.groupId} + scalecube-cluster-testlib + ${project.version} + test + diff --git a/examples/pom.xml b/examples/pom.xml index d0b2d934..6e15419b 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -33,18 +33,6 @@ scalecube-codec-jackson-smile ${project.version} - - org.apache.logging.log4j - log4j-slf4j-impl - - - org.apache.logging.log4j - log4j-core - - - org.apache.logging.log4j - log4j-jpl - diff --git a/examples/src/main/resources/log4j2.xml b/examples/src/main/resources/log4j2.xml deleted file mode 100644 index 53878182..00000000 --- a/examples/src/main/resources/log4j2.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - %level{length=1} %date{MMdd-HHmm:ss,SSS} %logger{1.} %message [%thread]%n - - - - - - - - - - - - - - - - - - - - - diff --git a/pom.xml b/pom.xml index 6e47e037..03bd44eb 100644 --- a/pom.xml +++ b/pom.xml @@ -37,6 +37,7 @@ 2020.0.32 2.18.2 + 1.7.36 5.3.1 5.9.3 @@ -77,6 +78,13 @@ import + + + org.slf4j + slf4j-api + ${slf4j.version} + + org.apache.logging.log4j @@ -85,57 +93,7 @@ pom import - - - - org.junit.jupiter - junit-jupiter-api - ${junit-jupiter.version} - - - - - org.junit.jupiter - junit-jupiter-engine - ${junit-jupiter.version} - test - - - org.junit.jupiter - junit-jupiter-params - ${junit-jupiter.version} - test - - - org.mockito - mockito-junit-jupiter - ${mockito-junit.version} - test - - - org.hamcrest - hamcrest-all - ${hamcrest.version} - test - - - io.projectreactor - reactor-test - test - - - org.apache.logging.log4j - log4j-core - test - - - org.apache.logging.log4j - log4j-jpl - test - - - diff --git a/transport-parent/pom.xml b/transport-parent/pom.xml index 061d3fdc..5b68aed3 100644 --- a/transport-parent/pom.xml +++ b/transport-parent/pom.xml @@ -24,6 +24,10 @@ io.projectreactor reactor-core + + org.slf4j + slf4j-api + diff --git a/transport-parent/transport-netty/src/main/java/io/scalecube/transport/netty/TransportImpl.java b/transport-parent/transport-netty/src/main/java/io/scalecube/transport/netty/TransportImpl.java index 86c66949..1d323276 100644 --- a/transport-parent/transport-netty/src/main/java/io/scalecube/transport/netty/TransportImpl.java +++ b/transport-parent/transport-netty/src/main/java/io/scalecube/transport/netty/TransportImpl.java @@ -14,8 +14,6 @@ import io.scalecube.cluster.transport.api.Message; import io.scalecube.cluster.transport.api.MessageCodec; import io.scalecube.cluster.transport.api.Transport; -import java.lang.System.Logger; -import java.lang.System.Logger.Level; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; @@ -24,6 +22,8 @@ import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import reactor.core.Disposable; import reactor.core.Disposables; import reactor.core.publisher.Flux; @@ -35,7 +35,7 @@ public final class TransportImpl implements Transport { - private static final Logger LOGGER = System.getLogger(Transport.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(Transport.class); private static final DistinctErrors DISTINCT_ERRORS = new DistinctErrors(Duration.ofMinutes(1)); @@ -108,13 +108,7 @@ private void init(DisposableServer server) { .then(doStop()) .doFinally(s -> onStop.emitEmpty(busyLooping(Duration.ofSeconds(3)))) .subscribe( - null, - ex -> - LOGGER.log( - Level.WARNING, - "[{0}][doStop] Exception occurred: {1}", - address, - ex.toString())); + null, ex -> LOGGER.warn("[{}][doStop] Exception occurred: {}", address, ex.toString())); } /** @@ -126,12 +120,8 @@ private void init(DisposableServer server) { public Mono start() { return Mono.deferContextual(context -> receiver.bind()) .doOnNext(this::init) - .doOnSuccess( - t -> LOGGER.log(Level.INFO, "[start][{0}] Bound cluster transport", t.address())) - .doOnError( - ex -> - LOGGER.log( - Level.ERROR, "[start][{0}] Exception occurred: {1}", address, ex.toString())) + .doOnSuccess(t -> LOGGER.info("[start][{}] Bound cluster transport", t.address())) + .doOnError(ex -> LOGGER.error("[start][{}] Exception occurred: {}", address, ex.toString())) .thenReturn(this) .cast(Transport.class) .contextWrite( @@ -163,13 +153,13 @@ public Mono stop() { private Mono doStop() { return Mono.defer( () -> { - LOGGER.log(Level.INFO, "[{0}][doStop] Stopping", address); + LOGGER.info("[{}][doStop] Stopping", address); // Complete incoming messages observable sink.emitComplete(busyLooping(Duration.ofSeconds(3))); return Flux.concatDelayError(closeServer(), shutdownLoopResources()) .then() .doFinally(s -> connections.clear()) - .doOnSuccess(avoid -> LOGGER.log(Level.INFO, "[{0}][doStop] Stopped", address)); + .doOnSuccess(avoid -> LOGGER.info("[{}][doStop] Stopped", address)); }); } @@ -223,8 +213,7 @@ private Message decodeMessage(ByteBuf byteBuf) { return messageCodec.deserialize(stream); } catch (Exception e) { if (!DISTINCT_ERRORS.contains(e)) { - LOGGER.log( - Level.WARNING, "[{0}][decodeMessage] Exception occurred: {1}", address, e.toString()); + LOGGER.warn("[{}][decodeMessage] Exception occurred: {}", address, e.toString()); } throw new DecoderException(e); } @@ -238,8 +227,7 @@ private ByteBuf encodeMessage(Message message) { } catch (Exception e) { byteBuf.release(); if (!DISTINCT_ERRORS.contains(e)) { - LOGGER.log( - Level.WARNING, "[{0}][encodeMessage] Exception occurred: {1}", address, e.toString()); + LOGGER.warn("[{}][encodeMessage] Exception occurred: {}", address, e.toString()); } throw new EncoderException(e); } @@ -256,9 +244,8 @@ private Mono connect(String remoteAddress) { .onDispose() .doOnTerminate(() -> connections.remove(remoteAddress)) .subscribe(); - LOGGER.log( - Level.DEBUG, - "[{0}][connect][success] remoteAddress: {1}, channel: {2}", + LOGGER.debug( + "[{}][connect][success] remoteAddress: {}, channel: {}", address, remoteAddress, connection.channel()); @@ -266,9 +253,8 @@ private Mono connect(String remoteAddress) { .doOnError( th -> { if (!DISTINCT_ERRORS.contains(th)) { - LOGGER.log( - Level.WARNING, - "[{0}][connect][error] remoteAddress: {1}, cause: {2}", + LOGGER.warn( + "[{}][connect][error] remoteAddress: {}, cause: {}", address, remoteAddress, th.toString()); @@ -284,19 +270,14 @@ private Mono closeServer() { if (server == null) { return Mono.empty(); } - LOGGER.log(Level.INFO, "[{0}][closeServer] Closing server channel", address); + LOGGER.info("[{}][closeServer] Closing server channel", address); return Mono.fromRunnable(server::dispose) .then(server.onDispose()) - .doOnSuccess( - avoid -> - LOGGER.log(Level.INFO, "[{0}][closeServer] Closed server channel", address)) + .doOnSuccess(avoid -> LOGGER.info("[{}][closeServer] Closed server channel", address)) .doOnError( e -> - LOGGER.log( - Level.WARNING, - "[{0}][closeServer] Exception occurred: {1}", - address, - e.toString())); + LOGGER.warn( + "[{}][closeServer] Exception occurred: {}", address, e.toString())); }); } @@ -344,7 +325,7 @@ public void onMessage(ByteBuf byteBuf) { final Message message = messageDecoder.apply(byteBuf); sink.emitNext(message, busyLooping(Duration.ofSeconds(3))); } catch (Exception e) { - LOGGER.log(Level.ERROR, "[{0}][onMessage] Exception occurred", address, e); + LOGGER.error("[{}][onMessage] Exception occurred", address, e); } } } diff --git a/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/BaseTest.java b/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/BaseTest.java index 57cc5877..ea05786c 100644 --- a/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/BaseTest.java +++ b/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/BaseTest.java @@ -6,28 +6,14 @@ import io.scalecube.cluster.utils.NetworkEmulatorTransport; import io.scalecube.transport.netty.tcp.TcpTransportFactory; import io.scalecube.transport.netty.websocket.WebsocketTransportFactory; -import java.lang.System.Logger; -import java.lang.System.Logger.Level; import java.time.Duration; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.TestInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; -/** Base test class. */ public class BaseTest { - protected static final Logger LOGGER = System.getLogger(BaseTest.class.getName()); - - @BeforeEach - public final void baseSetUp(TestInfo testInfo) { - LOGGER.log(Level.INFO, "***** Test started : " + testInfo.getDisplayName() + " *****"); - } - - @AfterEach - public final void baseTearDown(TestInfo testInfo) { - LOGGER.log(Level.INFO, "***** Test finished : " + testInfo.getDisplayName() + " *****"); - } + public static final Logger LOGGER = LoggerFactory.getLogger(BaseTest.class); /** * Sending message from src to destination. @@ -41,9 +27,8 @@ protected Mono send(Transport transport, String to, Message msg) { .send(to, msg) .doOnError( th -> - LOGGER.log( - Level.ERROR, - "Failed to send {0} to {1} from transport: {2}, cause: {3}", + LOGGER.error( + "Failed to send {} to {} from transport: {}, cause: {}", msg, to, transport, @@ -60,7 +45,7 @@ protected void destroyTransport(Transport transport) { try { transport.stop().block(Duration.ofSeconds(1)); } catch (Exception ex) { - LOGGER.log(Level.WARNING, "Failed to await transport termination: {0}", ex.toString()); + LOGGER.warn("Failed to await transport termination: {}", ex.toString()); } } } diff --git a/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/tcp/TcpTransportSendOrderTest.java b/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/tcp/TcpTransportSendOrderTest.java index 532af84c..417c6f0b 100644 --- a/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/tcp/TcpTransportSendOrderTest.java +++ b/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/tcp/TcpTransportSendOrderTest.java @@ -5,7 +5,6 @@ import io.scalecube.cluster.transport.api.Message; import io.scalecube.cluster.transport.api.Transport; import io.scalecube.transport.netty.BaseTest; -import java.lang.System.Logger.Level; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; @@ -46,7 +45,7 @@ public void testSendOrderSingleThreadWithoutPromises(TestInfo testInfo) throws E int sentPerIteration = 1000; long[] iterationTimeSeries = new long[iterationNum - 1]; for (int i = 0; i < iterationNum; i++) { - LOGGER.log(Level.DEBUG, "####### {0} : iteration = {1}", testInfo.getDisplayName(), i); + LOGGER.debug("####### {} : iteration = {}", testInfo.getDisplayName(), i); client = createTcpTransport(); final List received = new ArrayList<>(); @@ -66,7 +65,7 @@ public void testSendOrderSingleThreadWithoutPromises(TestInfo testInfo) throws E Message message = Message.withQualifier("q" + j).build(); client .send(server.address(), message) - .subscribe(null, th -> LOGGER.log(Level.ERROR, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.error("Failed to send message", th)); } latch.await(20, TimeUnit.SECONDS); long iterationTime = System.currentTimeMillis() - startAt; @@ -75,7 +74,7 @@ public void testSendOrderSingleThreadWithoutPromises(TestInfo testInfo) throws E } assertSendOrder(sentPerIteration, received); - LOGGER.log(Level.DEBUG, "Iteration time: {0} ms", iterationTime); + LOGGER.debug("Iteration time: {} ms", iterationTime); serverSubscriber.dispose(); destroyTransport(client); @@ -83,7 +82,7 @@ public void testSendOrderSingleThreadWithoutPromises(TestInfo testInfo) throws E LongSummaryStatistics iterationTimeStats = LongStream.of(iterationTimeSeries).summaryStatistics(); - LOGGER.log(Level.DEBUG, "Iteration time stats (ms): {0}", iterationTimeStats); + LOGGER.debug("Iteration time stats (ms): {}", iterationTimeStats); } @Test @@ -95,7 +94,7 @@ public void testSendOrderSingleThread(TestInfo testInfo) throws Exception { long[] iterationTimeSeries = new long[iterationNum - 1]; List totalSentTimeSeries = new ArrayList<>(sentPerIteration * (iterationNum - 1)); for (int i = 0; i < iterationNum; i++) { - LOGGER.log(Level.DEBUG, "####### {0} : iteration = {1}", testInfo.getDisplayName(), i); + LOGGER.debug("####### {} : iteration = {}", testInfo.getDisplayName(), i); List iterSentTimeSeries = new ArrayList<>(sentPerIteration); client = createTcpTransport(); @@ -120,9 +119,8 @@ public void testSendOrderSingleThread(TestInfo testInfo) throws Exception { .subscribe( avoid -> iterSentTimeSeries.add(System.currentTimeMillis() - sentAt), th -> - LOGGER.log( - Level.ERROR, - "Failed to send message in {0} ms", + LOGGER.error( + "Failed to send message in {} ms", System.currentTimeMillis() - sentAt, th)); } @@ -139,15 +137,15 @@ public void testSendOrderSingleThread(TestInfo testInfo) throws Exception { LongSummaryStatistics iterSentTimeStats = iterSentTimeSeries.stream().mapToLong(v -> v).summaryStatistics(); if (i == 0) { // warm up iteration - LOGGER.log(Level.DEBUG, "Warm up iteration time: {0} ms", iterationTime); - LOGGER.log(Level.DEBUG, "Sent time stats warm up iter (ms): {0}", iterSentTimeStats); + LOGGER.debug("Warm up iteration time: {} ms", iterationTime); + LOGGER.debug("Sent time stats warm up iter (ms): {}", iterSentTimeStats); } else { totalSentTimeSeries.addAll(iterSentTimeSeries); LongSummaryStatistics totalSentTimeStats = totalSentTimeSeries.stream().mapToLong(v -> v).summaryStatistics(); - LOGGER.log(Level.DEBUG, "Iteration time: {0} ms", iterationTime); - LOGGER.log(Level.DEBUG, "Sent time stats iter (ms): {0}", iterSentTimeStats); - LOGGER.log(Level.DEBUG, "Sent time stats total (ms): {0}", totalSentTimeStats); + LOGGER.debug("Iteration time: {} ms", iterationTime); + LOGGER.debug("Sent time stats iter (ms): {}", iterSentTimeStats); + LOGGER.debug("Sent time stats total (ms): {}", totalSentTimeStats); } serverSubscriber.dispose(); @@ -156,7 +154,7 @@ public void testSendOrderSingleThread(TestInfo testInfo) throws Exception { LongSummaryStatistics iterationTimeStats = LongStream.of(iterationTimeSeries).summaryStatistics(); - LOGGER.log(Level.DEBUG, "Iteration time stats (ms): {0}", iterationTimeStats); + LOGGER.debug("Iteration time stats (ms): {}", iterationTimeStats); } @Test @@ -165,7 +163,7 @@ public void testSendOrderMultiThread(TestInfo testInfo) throws Exception { final int total = 1000; for (int i = 0; i < 10; i++) { - LOGGER.log(Level.DEBUG, "####### {0} : iteration = {1}", testInfo.getDisplayName(), i); + LOGGER.debug("####### {} : iteration = {}", testInfo.getDisplayName(), i); ExecutorService exec = Executors.newFixedThreadPool( 4, @@ -229,7 +227,7 @@ private Callable sender(int id, Transport client, String address, int tota Message message = Message.withQualifier("q").correlationId(correlationId).build(); client.send(address, message).block(Duration.ofSeconds(3)); } catch (Exception e) { - LOGGER.log(Level.ERROR, "Failed to send message: j = {0} id = {1}", j, id, e); + LOGGER.error("Failed to send message: j = {} id = {}", j, id, e); throw Exceptions.propagate(e); } } diff --git a/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/tcp/TcpTransportTest.java b/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/tcp/TcpTransportTest.java index 37ac22d5..9c5ed4b9 100644 --- a/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/tcp/TcpTransportTest.java +++ b/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/tcp/TcpTransportTest.java @@ -10,7 +10,6 @@ import io.scalecube.cluster.utils.NetworkEmulatorTransport; import io.scalecube.transport.netty.BaseTest; import java.io.IOException; -import java.lang.System.Logger.Level; import java.net.UnknownHostException; import java.time.Duration; import java.util.ArrayList; @@ -59,7 +58,7 @@ public void testUnresolvedHostConnection() { public void testInteractWithNoConnection(TestInfo testInfo) { String serverAddress = "localhost:49255"; for (int i = 0; i < 10; i++) { - LOGGER.log(Level.DEBUG, "####### {0} : iteration = {1}", testInfo.getDisplayName(), i); + LOGGER.debug("####### {} : iteration = {}", testInfo.getDisplayName(), i); client = createTcpTransport(); @@ -147,7 +146,7 @@ public void testPingPongOnSingleChannel() throws Exception { Message echo = Message.withData("echo/" + message.qualifier()).build(); server .send(message.sender(), echo) - .subscribe(null, th -> LOGGER.log(Level.ERROR, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.error("Failed to send message", th)); } }); @@ -159,10 +158,10 @@ public void testPingPongOnSingleChannel() throws Exception { client .send(server.address(), q1) - .subscribe(null, th -> LOGGER.log(Level.ERROR, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.error("Failed to send message", th)); client .send(server.address(), q2) - .subscribe(null, th -> LOGGER.log(Level.ERROR, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.error("Failed to send message", th)); List target = targetFuture.get(1, TimeUnit.SECONDS); assertNotNull(target); @@ -217,7 +216,7 @@ public void testPingPongOnSeparateChannel() throws Exception { Message echo = Message.withData("echo/" + message.qualifier()).build(); server .send(message.sender(), echo) - .subscribe(null, th -> LOGGER.log(Level.ERROR, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.error("Failed to send message", th)); } }); @@ -229,10 +228,10 @@ public void testPingPongOnSeparateChannel() throws Exception { client .send(server.address(), q1) - .subscribe(null, th -> LOGGER.log(Level.ERROR, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.error("Failed to send message", th)); client .send(server.address(), q2) - .subscribe(null, th -> LOGGER.log(Level.ERROR, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.error("Failed to send message", th)); List target = targetFuture.get(1, TimeUnit.SECONDS); assertNotNull(target); @@ -282,7 +281,7 @@ public void testObserverThrowsException() throws Exception { Message echo = Message.withData("echo/" + message.qualifier()).build(); server .send(message.sender(), echo) - .subscribe(null, th -> LOGGER.log(Level.ERROR, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.error("Failed to send message", th)); } }, Throwable::printStackTrace); @@ -293,7 +292,7 @@ public void testObserverThrowsException() throws Exception { Message message = Message.withData("throw").build(); client .send(server.address(), message) - .subscribe(null, th -> LOGGER.log(Level.ERROR, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.error("Failed to send message", th)); Message message0 = null; try { message0 = messageFuture0.get(1, TimeUnit.SECONDS); diff --git a/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/websocket/WebsocketTransportSendOrderTest.java b/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/websocket/WebsocketTransportSendOrderTest.java index 9b353247..8ed11235 100644 --- a/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/websocket/WebsocketTransportSendOrderTest.java +++ b/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/websocket/WebsocketTransportSendOrderTest.java @@ -5,7 +5,6 @@ import io.scalecube.cluster.transport.api.Message; import io.scalecube.cluster.transport.api.Transport; import io.scalecube.transport.netty.BaseTest; -import java.lang.System.Logger.Level; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; @@ -46,7 +45,7 @@ public void testSendOrderSingleThreadWithoutPromises(TestInfo testInfo) throws E int sentPerIteration = 1000; long[] iterationTimeSeries = new long[iterationNum - 1]; for (int i = 0; i < iterationNum; i++) { - LOGGER.log(Level.DEBUG, "####### {0} : iteration = {1}", testInfo.getDisplayName(), i); + LOGGER.debug("####### {} : iteration = {}", testInfo.getDisplayName(), i); client = createWebsocketTransport(); final List received = new ArrayList<>(); @@ -66,7 +65,7 @@ public void testSendOrderSingleThreadWithoutPromises(TestInfo testInfo) throws E Message message = Message.withQualifier("q" + j).build(); client .send(server.address(), message) - .subscribe(null, th -> LOGGER.log(Level.ERROR, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.error("Failed to send message", th)); } latch.await(20, TimeUnit.SECONDS); long iterationTime = System.currentTimeMillis() - startAt; @@ -75,7 +74,7 @@ public void testSendOrderSingleThreadWithoutPromises(TestInfo testInfo) throws E } assertSendOrder(sentPerIteration, received); - LOGGER.log(Level.DEBUG, "Iteration time: {0} ms", iterationTime); + LOGGER.debug("Iteration time: {} ms", iterationTime); serverSubscriber.dispose(); destroyTransport(client); @@ -83,7 +82,7 @@ public void testSendOrderSingleThreadWithoutPromises(TestInfo testInfo) throws E LongSummaryStatistics iterationTimeStats = LongStream.of(iterationTimeSeries).summaryStatistics(); - LOGGER.log(Level.DEBUG, "Iteration time stats (ms): {0}", iterationTimeStats); + LOGGER.debug("Iteration time stats (ms): {}", iterationTimeStats); } @Test @@ -95,7 +94,7 @@ public void testSendOrderSingleThread(TestInfo testInfo) throws Exception { long[] iterationTimeSeries = new long[iterationNum - 1]; List totalSentTimeSeries = new ArrayList<>(sentPerIteration * (iterationNum - 1)); for (int i = 0; i < iterationNum; i++) { - LOGGER.log(Level.DEBUG, "####### {0} : iteration = {1}", testInfo.getDisplayName(), i); + LOGGER.debug("####### {} : iteration = {}", testInfo.getDisplayName(), i); List iterSentTimeSeries = new ArrayList<>(sentPerIteration); client = createWebsocketTransport(); @@ -120,9 +119,8 @@ public void testSendOrderSingleThread(TestInfo testInfo) throws Exception { .subscribe( avoid -> iterSentTimeSeries.add(System.currentTimeMillis() - sentAt), th -> - LOGGER.log( - Level.ERROR, - "Failed to send message in {0} ms", + LOGGER.error( + "Failed to send message in {} ms", System.currentTimeMillis() - sentAt, th)); } @@ -139,15 +137,15 @@ public void testSendOrderSingleThread(TestInfo testInfo) throws Exception { LongSummaryStatistics iterSentTimeStats = iterSentTimeSeries.stream().mapToLong(v -> v).summaryStatistics(); if (i == 0) { // warm up iteration - LOGGER.log(Level.DEBUG, "Warm up iteration time: {0} ms", iterationTime); - LOGGER.log(Level.DEBUG, "Sent time stats warm up iter (ms): {0}", iterSentTimeStats); + LOGGER.debug("Warm up iteration time: {} ms", iterationTime); + LOGGER.debug("Sent time stats warm up iter (ms): {}", iterSentTimeStats); } else { totalSentTimeSeries.addAll(iterSentTimeSeries); LongSummaryStatistics totalSentTimeStats = totalSentTimeSeries.stream().mapToLong(v -> v).summaryStatistics(); - LOGGER.log(Level.DEBUG, "Iteration time: {0} ms", iterationTime); - LOGGER.log(Level.DEBUG, "Sent time stats iter (ms): {0}", iterSentTimeStats); - LOGGER.log(Level.DEBUG, "Sent time stats total (ms): {0}", totalSentTimeStats); + LOGGER.debug("Iteration time: {} ms", iterationTime); + LOGGER.debug("Sent time stats iter (ms): {}", iterSentTimeStats); + LOGGER.debug("Sent time stats total (ms): {}", totalSentTimeStats); } serverSubscriber.dispose(); @@ -156,7 +154,7 @@ public void testSendOrderSingleThread(TestInfo testInfo) throws Exception { LongSummaryStatistics iterationTimeStats = LongStream.of(iterationTimeSeries).summaryStatistics(); - LOGGER.log(Level.DEBUG, "Iteration time stats (ms): {0}", iterationTimeStats); + LOGGER.debug("Iteration time stats (ms): {}", iterationTimeStats); } @Test @@ -165,7 +163,7 @@ public void testSendOrderMultiThread(TestInfo testInfo) throws Exception { final int total = 1000; for (int i = 0; i < 10; i++) { - LOGGER.log(Level.DEBUG, "####### {0} : iteration = {1}", testInfo.getDisplayName(), i); + LOGGER.debug("####### {} : iteration = {}", testInfo.getDisplayName(), i); ExecutorService exec = Executors.newFixedThreadPool( 4, @@ -229,7 +227,7 @@ private Callable sender(int id, Transport client, String address, int tota Message message = Message.withQualifier("q").correlationId(correlationId).build(); client.send(address, message).block(Duration.ofSeconds(3)); } catch (Exception e) { - LOGGER.log(Level.ERROR, "Failed to send message: j = {0} id = {1}", j, id, e); + LOGGER.error("Failed to send message: j = {} id = {}", j, id, e); throw Exceptions.propagate(e); } } diff --git a/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/websocket/WebsocketTransportTest.java b/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/websocket/WebsocketTransportTest.java index 9d8021ca..e2c03dfb 100644 --- a/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/websocket/WebsocketTransportTest.java +++ b/transport-parent/transport-netty/src/test/java/io/scalecube/transport/netty/websocket/WebsocketTransportTest.java @@ -10,7 +10,6 @@ import io.scalecube.cluster.utils.NetworkEmulatorTransport; import io.scalecube.transport.netty.BaseTest; import java.io.IOException; -import java.lang.System.Logger.Level; import java.net.UnknownHostException; import java.time.Duration; import java.util.ArrayList; @@ -59,7 +58,7 @@ public void testUnresolvedHostConnection() { public void testInteractWithNoConnection(TestInfo testInfo) { String serverAddress = "localhost:49255"; for (int i = 0; i < 10; i++) { - LOGGER.log(Level.DEBUG, "####### {0} : iteration = {1}", testInfo.getDisplayName(), i); + LOGGER.debug("####### {} : iteration = {}", testInfo.getDisplayName(), i); client = createWebsocketTransport(); @@ -147,7 +146,7 @@ public void testPingPongOnSingleChannel() throws Exception { Message echo = Message.withData("echo/" + message.qualifier()).build(); server .send(message.sender(), echo) - .subscribe(null, th -> LOGGER.log(Level.DEBUG, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.debug("Failed to send message", th)); } }); @@ -159,10 +158,10 @@ public void testPingPongOnSingleChannel() throws Exception { client .send(server.address(), q1) - .subscribe(null, th -> LOGGER.log(Level.ERROR, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.error("Failed to send message", th)); client .send(server.address(), q2) - .subscribe(null, th -> LOGGER.log(Level.ERROR, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.error("Failed to send message", th)); List target = targetFuture.get(1, TimeUnit.SECONDS); assertNotNull(target); @@ -217,7 +216,7 @@ public void testPingPongOnSeparateChannel() throws Exception { Message echo = Message.withData("echo/" + message.qualifier()).build(); server .send(message.sender(), echo) - .subscribe(null, th -> LOGGER.log(Level.ERROR, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.error("Failed to send message", th)); } }); @@ -229,10 +228,10 @@ public void testPingPongOnSeparateChannel() throws Exception { client .send(server.address(), q1) - .subscribe(null, th -> LOGGER.log(Level.ERROR, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.error("Failed to send message", th)); client .send(server.address(), q2) - .subscribe(null, th -> LOGGER.log(Level.ERROR, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.error("Failed to send message", th)); List target = targetFuture.get(1, TimeUnit.SECONDS); assertNotNull(target); @@ -282,7 +281,7 @@ public void testObserverThrowsException() throws Exception { Message echo = Message.withData("echo/" + message.qualifier()).build(); server .send(message.sender(), echo) - .subscribe(null, th -> LOGGER.log(Level.ERROR, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.error("Failed to send message", th)); } }, Throwable::printStackTrace); @@ -293,7 +292,7 @@ public void testObserverThrowsException() throws Exception { Message message = Message.withData("throw").build(); client .send(server.address(), message) - .subscribe(null, th -> LOGGER.log(Level.ERROR, "Failed to send message", th)); + .subscribe(null, th -> LOGGER.error("Failed to send message", th)); Message message0 = null; try { message0 = messageFuture0.get(1, TimeUnit.SECONDS);