Skip to content

Commit

Permalink
Loggable trait
Browse files Browse the repository at this point in the history
  • Loading branch information
olle committed Nov 30, 2024
1 parent c4f22ae commit 4629a01
Show file tree
Hide file tree
Showing 10 changed files with 58 additions and 39 deletions.
16 changes: 8 additions & 8 deletions src/main/java/com/studiomediatech/queryresponse/Query.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.type.TypeFactory;

import com.studiomediatech.queryresponse.util.Logging;
import com.studiomediatech.queryresponse.util.Loggable;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
Expand All @@ -34,7 +34,7 @@
* @param <T>
* expected type of the coerced result elements.
*/
class Query<T> implements MessageListener, Logging {
class Query<T> implements MessageListener, Loggable {

private static final String HEADER_X_QR_PUBLISHED = RabbitFacade.HEADER_X_QR_PUBLISHED;

Expand Down Expand Up @@ -84,7 +84,7 @@ protected Query(String queueName) {
public void onMessage(Message message) {

MessageProperties properties = message.getMessageProperties();
log().info("|--> Received response message: {}", properties);
logger().info("|--> Received response message: {}", properties);
measureLatency(properties.getHeader(HEADER_X_QR_PUBLISHED), System.currentTimeMillis());
handleResponseEnvelope(parseMessage(message));
}
Expand All @@ -102,7 +102,7 @@ private ConsumedResponseEnvelope<T> parseMessage(Message message) {
JavaType type = TypeFactory.defaultInstance().constructParametricType(ConsumedResponseEnvelope.class,
responseType);
ConsumedResponseEnvelope<T> response = reader.forType(type).readValue(message.getBody());
log().debug("Received response: {}", response);
logger().debug("Received response: {}", response);

return response;
} catch (IOException ex) {
Expand All @@ -111,7 +111,7 @@ private ConsumedResponseEnvelope<T> parseMessage(Message message) {
onError.accept(new IllegalArgumentException(errorMessage, ex));
}

log().error("Failed to parse received response.", ex);
logger().error("Failed to parse received response.", ex);
}

return ConsumedResponseEnvelope.empty();
Expand All @@ -120,7 +120,7 @@ private ConsumedResponseEnvelope<T> parseMessage(Message message) {
void handleResponseEnvelope(ConsumedResponseEnvelope<T> envelope) {

if (envelope.elements.isEmpty()) {
log().warn("Received empty response: {}", envelope);
logger().warn("Received empty response: {}", envelope);

return;
}
Expand Down Expand Up @@ -211,7 +211,7 @@ public Collection<T> accept(RabbitFacade facade, Statistics stats) throws Runtim
}

// Reset interrupted state, before moving on.
log().error("Sleep interrupted with still {} ms to go", wait, e);
logger().error("Sleep interrupted with still {} ms to go", wait, e);
Thread.currentThread().interrupt();

/*
Expand Down Expand Up @@ -263,7 +263,7 @@ private void publishQuery(RabbitFacade facade) {
this.onError.accept(ex);
}

log().error("Failed to publish query message", ex);
logger().error("Failed to publish query message", ex);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.studiomediatech.queryresponse;

import com.studiomediatech.queryresponse.util.Logging;
import com.studiomediatech.queryresponse.util.Loggable;

import org.springframework.beans.BeansException;

Expand All @@ -13,7 +13,7 @@
/**
* Provides a way to register and execute queries.
*/
class QueryRegistry implements ApplicationContextAware, Logging {
class QueryRegistry implements ApplicationContextAware, Loggable {

// WARNING: Non-exemplary use of static supplier, for lazy access to bean instance.
protected static Supplier<QueryRegistry> instance = () -> null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.env.Environment;

import com.studiomediatech.queryresponse.util.Logging;
import com.studiomediatech.queryresponse.util.Loggable;

/**
* Configures the required components for a Query/Response client, ensuring the availability of the necessary AMQP
Expand All @@ -27,7 +27,7 @@
@AutoConfigureAfter(RabbitAutoConfiguration.class)
@Import({ RabbitAutoConfiguration.class })
@EnableConfigurationProperties(QueryResponseConfigurationProperties.class)
class QueryResponseConfiguration implements Logging {
class QueryResponseConfiguration implements Loggable {

private final QueryResponseConfigurationProperties props;

Expand Down Expand Up @@ -69,7 +69,7 @@ RabbitFacade rabbitFacade(RabbitAdmin rabbitAdmin, ConnectionFactory connectionF
@Bean
QueryResponseTopicExchange queryResponseTopicExchange() {

return log(new QueryResponseTopicExchange(props.getExchange().getName()));
return info(new QueryResponseTopicExchange(props.getExchange().getName()));
}

@Bean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@
import org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer;
import org.springframework.context.support.GenericApplicationContext;

import com.studiomediatech.queryresponse.util.Logging;
import com.studiomediatech.queryresponse.util.Loggable;

/**
* Provides an abstraction between the use of RabbitMQ and the capabilities in Spring Boot AMQP, and the structured
* registry code in this library.
*/
class RabbitFacade implements Logging {
class RabbitFacade implements Loggable {

public static final String HEADER_X_QR_PUBLISHED = "x-qr-published";

Expand Down Expand Up @@ -61,7 +61,7 @@ public void declareQueue(Query<?> query) {

private void declareAndRegisterQueue(NamingStrategy name) {

AnonymousQueue queue = log(new AnonymousQueue(name));
AnonymousQueue queue = info(new AnonymousQueue(name));
admin.declareQueue(queue);
ctx.registerBean(queue.getActualName(), AnonymousQueue.class, () -> queue);
}
Expand All @@ -76,7 +76,7 @@ public void declareBinding(Response<?> response) {

private void declareAndRegisterBinding(String queueName, String routingKey) {

Binding binding = log(
Binding binding = info(
new Binding(queueName, DestinationType.QUEUE, queriesExchange.getName(), routingKey, null));
admin.declareBinding(binding);
ctx.registerBean(queueName + "-binding", Binding.class, () -> binding);
Expand Down Expand Up @@ -193,7 +193,7 @@ public void publishResponse(String exchange, String routingKey, Message message)
this.template.send(exchange, routingKey, m);
logPublished("response", routingKey, m);
} catch (RuntimeException e) {
log().error("Failed to publish response", e);
logger().error("Failed to publish response", e);
}
}

Expand Down
10 changes: 5 additions & 5 deletions src/main/java/com/studiomediatech/queryresponse/Response.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;

import com.studiomediatech.queryresponse.util.Logging;
import com.studiomediatech.queryresponse.util.Loggable;

import org.springframework.amqp.core.Address;
import org.springframework.amqp.core.Message;
Expand All @@ -28,7 +28,7 @@
* @param <T>
* type of the provided response elements.
*/
class Response<T> implements MessageListener, Logging {
class Response<T> implements MessageListener, Loggable {

private static final String HEADER_X_QR_PUBLISHED = RabbitFacade.HEADER_X_QR_PUBLISHED;

Expand Down Expand Up @@ -69,7 +69,7 @@ public void onMessage(Message message) {

try {
MessageProperties properties = message.getMessageProperties();
log().info("|--> Consumed query: " + properties.getReceivedRoutingKey());
logger().info("|--> Consumed query: " + properties.getReceivedRoutingKey());
measureLatency(properties.getHeader(HEADER_X_QR_PUBLISHED), System.currentTimeMillis());

List<Response<T>.PublishedResponseEnvelope<T>> responses = new ArrayList<>();
Expand All @@ -80,7 +80,7 @@ public void onMessage(Message message) {
responses.addAll(buildResponses());
}

log().debug("Prepared response(s) {}", responses);
logger().debug("Prepared response(s) {}", responses);

for (Response<T>.PublishedResponseEnvelope<T> response : responses) {
byte[] body = writer.writeValueAsBytes(response);
Expand All @@ -97,7 +97,7 @@ public void onMessage(Message message) {
incrementPublishedResponseCounterStats();
}
} catch (RuntimeException | JsonProcessingException e) {
log().error("Failed to publish response message", e);
logger().error("Failed to publish response message", e);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.studiomediatech.queryresponse;

import com.studiomediatech.queryresponse.util.Logging;
import com.studiomediatech.queryresponse.util.Loggable;

import org.springframework.beans.BeansException;

Expand All @@ -12,7 +12,7 @@
/**
* Provides a way to create and register responses.
*/
class ResponseRegistry implements ApplicationContextAware, Logging {
class ResponseRegistry implements ApplicationContextAware, Loggable {

// WARNING: Non-exemplary use of static supplier, for lazy access to bean instance.
protected static Supplier<ResponseRegistry> instance = () -> null;
Expand Down Expand Up @@ -58,9 +58,9 @@ protected <T> void doAccept(Response<T> response) {
facade.addListener(response);

response.accept(facade, stats);
log().info("Registered {}", response);
logger().info("Registered {}", response);
} catch (Throwable th) {
log().error("Failed to register response", th);
logger().error("Failed to register response", th);
facade.removeListener(response);
facade.removeQueue(response);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.studiomediatech.queryresponse.util.DurationFormatter;
import com.studiomediatech.queryresponse.util.Logging;
import com.studiomediatech.queryresponse.util.Loggable;

class Statistics implements Logging {
class Statistics implements Loggable {

private static final ObjectWriter writer = new ObjectMapper().writer();

Expand Down Expand Up @@ -107,7 +107,7 @@ protected void publishStats() {

facade.publishStats(message, routingKey);
} catch (RuntimeException | JsonProcessingException ex) {
log().error("Failed to publish stats", ex);
logger().error("Failed to publish stats", ex);
}

this.scheduler.schedule(this::publishStats, props.getStats().getDelay(), TimeUnit.MILLISECONDS);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@
/**
* Trait for logging, with convenient access to a default instance based logger.
*/
public interface Logging {
public interface Loggable {

/**
* Provides a default logger
*
* @return a logger instance, never {@code null}
*/
default Logger log() {
default Logger logger() {

return LoggerFactory.getLogger(getClass());
}
Expand All @@ -30,9 +30,9 @@ default Logger log() {
*
* @return the current logger, for chaining
*/
default <T extends Declarable> T log(T obj) {
default <T extends Declarable> T info(T obj) {

log().info("//> Declared {}", obj);
logger().info("//> Declared {}", obj);

return obj;
}
Expand All @@ -50,7 +50,7 @@ default <T extends Declarable> T log(T obj) {
*/
default void debugLogPublished(String type, String routingKey, Message message) {

log().debug("|<-- Published {}: {} - {}", type, routingKey, toStringRedacted(message));
logger().debug("|<-- Published {}: {} - {}", type, routingKey, toStringRedacted(message));
}

/**
Expand All @@ -66,10 +66,10 @@ default void debugLogPublished(String type, String routingKey, Message message)
*/
default void logPublished(String type, String routingKey, Message message) {

if (log().isTraceEnabled()) {
log().debug("|<-- Published {}: {} - {}", type, routingKey, message);
if (logger().isTraceEnabled()) {
logger().debug("|<-- Published {}: {} - {}", type, routingKey, message);
} else {
log().info("|<-- Published {}: {} - {}", type, routingKey, toStringRedacted(message));
logger().info("|<-- Published {}: {} - {}", type, routingKey, toStringRedacted(message));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public LogMockingRabbitFacade(Logger log) {
}

@Override
public Logger log() {
public Logger logger() {

return this.log;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.studiomediatech.queryresponse.util;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;
import org.slf4j.Logger;

class LoggableTest {

@Test
void ensureExposesLogger() {
(new Loggable() {
void test() {
assertThat(logger()).isNotNull().isInstanceOfAny(Logger.class);
}
}).test();
}

}

0 comments on commit 4629a01

Please sign in to comment.