Skip to content

Commit

Permalink
#169 - Use parametrised log statements
Browse files Browse the repository at this point in the history
  • Loading branch information
gazbert committed Nov 13, 2024
1 parent 46b7c81 commit 4b45b96
Show file tree
Hide file tree
Showing 6 changed files with 58 additions and 61 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -63,28 +63,26 @@ public static ExchangeConfigImpl buildConfig(ExchangeConfig exchangeConfig) {
exchangeApiNetworkConfig.setNonFatalErrorCodes(nonFatalErrorCodes);
} else {
log.info(
"No (optional) NetworkConfiguration NonFatalErrorCodes have been set for "
+ "Exchange Adapter: "
+ exchangeConfig.getAdapter());
"No (optional) NetworkConfiguration NonFatalErrorCodes have been set for Exchange Adapter: {}",
exchangeConfig.getAdapter());
}

final List<String> nonFatalErrorMessages = networkConfig.getNonFatalErrorMessages();
if (nonFatalErrorMessages != null && !nonFatalErrorMessages.isEmpty()) {
exchangeApiNetworkConfig.setNonFatalErrorMessages(nonFatalErrorMessages);
} else {
log.info(
"No (optional) NetworkConfiguration NonFatalErrorMessages have been set for "
+ "Exchange Adapter: "
+ exchangeConfig.getAdapter());
"No (optional) NetworkConfiguration NonFatalErrorMessages have been set for Exchange Adapter: {}",
exchangeConfig.getAdapter());
}

exchangeApiConfig.setNetworkConfig(exchangeApiNetworkConfig);
log.info("NetworkConfiguration has been set: " + exchangeApiNetworkConfig);
log.info("NetworkConfiguration has been set: {}", exchangeApiNetworkConfig);

} else {
log.info(
"No (optional) NetworkConfiguration has been set for Exchange Adapter: "
+ exchangeConfig.getAdapter());
"No (optional) NetworkConfiguration has been set for Exchange Adapter: {}",
exchangeConfig.getAdapter());
}

final Map<String, String> authenticationConfig = exchangeConfig.getAuthenticationConfig();
Expand All @@ -99,18 +97,19 @@ public static ExchangeConfigImpl buildConfig(ExchangeConfig exchangeConfig) {

} else {
log.info(
"No (optional) AuthenticationConfiguration has been set for Exchange Adapter: "
+ exchangeConfig.getAdapter());
"No (optional) AuthenticationConfiguration has been set for Exchange Adapter: {}",
exchangeConfig.getAdapter());
}

final Map<String, String> otherConfig = exchangeConfig.getOtherConfig();
if (otherConfig != null) {
final OtherConfigImpl exchangeApiOtherConfig = new OtherConfigImpl();
exchangeApiOtherConfig.setItems(otherConfig);
exchangeApiConfig.setOtherConfig(exchangeApiOtherConfig);
log.info("Other Exchange Adapter config has been set: " + exchangeApiOtherConfig);
log.info("Other Exchange Adapter config has been set: {}", exchangeApiOtherConfig);
} else {
log.info("No Other config has been set for Exchange Adapter: " + exchangeConfig.getAdapter());
log.info(
"No Other config has been set for Exchange Adapter: {}", exchangeConfig.getAdapter());
}

return exchangeApiConfig;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public List<TradingStrategy> buildStrategies(
final Map<String, StrategyConfig> tradingStrategyConfigs = new HashMap<>();
for (final StrategyConfig strategy : strategies) {
tradingStrategyConfigs.put(strategy.getId(), strategy);
log.info("Registered Trading Strategy with Trading Engine: Id=" + strategy.getId());
log.info("Registered Trading Strategy with Trading Engine: Id={}", strategy.getId());
}

// Set logic only as crude mechanism for checking for duplicate Markets.
Expand All @@ -94,7 +94,7 @@ public List<TradingStrategy> buildStrategies(
for (final MarketConfig market : markets) {
final String marketName = market.getName();
if (!market.isEnabled()) {
log.info(marketName + " market is NOT enabled for trading - skipping to next market...");
log.info("{} market is NOT enabled for trading - skipping to next market...", marketName);
continue;
}

Expand All @@ -108,12 +108,12 @@ public List<TradingStrategy> buildStrategies(
throw new IllegalArgumentException(errorMsg);
} else {
log.info(
"Registered Market with Trading Engine: Id=" + market.getId() + ", Name=" + marketName);
"Registered Market with Trading Engine: Id={}, Name={}", market.getId(), marketName);
}

// Get the strategy to use for this Market
final String strategyToUse = market.getTradingStrategyId();
log.info("Market Trading Strategy Id to use: " + strategyToUse);
log.info("Market Trading Strategy Id to use: {}", strategyToUse);

if (tradingStrategyConfigs.containsKey(strategyToUse)) {
final StrategyConfig tradingStrategy = tradingStrategyConfigs.get(strategyToUse);
Expand All @@ -123,9 +123,9 @@ public List<TradingStrategy> buildStrategies(
tradingStrategyConfig.setItems(configItems);
} else {
log.info(
"No (optional) configuration has been set for Trading Strategy: " + strategyToUse);
"No (optional) configuration has been set for Trading Strategy: {}", strategyToUse);
}
log.info("StrategyConfigImpl (optional): " + tradingStrategyConfig);
log.info("StrategyConfigImpl (optional): {}", tradingStrategyConfig);

/*
* Load the Trading Strategy impl, instantiate it, set its config, and store in the
Expand All @@ -136,13 +136,10 @@ public List<TradingStrategy> buildStrategies(
strategyImpl.init(exchangeAdapter, tradingMarket, tradingStrategyConfig);

log.info(
"Initialized trading strategy successfully. Name: ["
+ tradingStrategy.getName()
+ "] Class: ["
+ tradingStrategy.getClassName()
+ "] Bean: ["
+ tradingStrategy.getBeanName()
+ "]");
"Initialized trading strategy successfully. Name: [{}] Class: [{}] Bean: [{}]",
tradingStrategy.getName(),
tradingStrategy.getClassName(),
tradingStrategy.getBeanName());

tradingStrategiesToExecute.add(strategyImpl);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ public class TradingEngine {
private static final String DETAILS_ERROR_MSG_LABEL = " Details: ";
private static final String CAUSE_ERROR_MSG_LABEL = " Cause: ";

private static final String THREAD_INTERRUPTED_WARN_MSG =
"Control Loop thread interrupted when sleeping before next trade cycle";

private static final Object IS_RUNNING_MONITOR = new Object();
private Thread engineThread;
private volatile boolean keepAlive = true;
Expand Down Expand Up @@ -160,7 +163,7 @@ private void init() {
* The code fails hard and fast if an unexpected occurs. Network exceptions *should* recover.
*/
private void runMainControlLoop() {
log.info("Starting Trading Engine for " + engineConfig.getBotId() + " ...");
log.info("Starting Trading Engine for {} ...", engineConfig.getBotId());
while (keepAlive) {
try {
log.info("*** Starting next trade cycle... ***");
Expand All @@ -171,7 +174,8 @@ private void runMainControlLoop() {
}

for (final TradingStrategy tradingStrategy : tradingStrategies) {
log.info("Executing Trading Strategy ---> " + tradingStrategy.getClass().getSimpleName());
log.info(
"Executing Trading Strategy ---> {}", tradingStrategy.getClass().getSimpleName());
tradingStrategy.execute();
}

Expand All @@ -192,7 +196,7 @@ private void runMainControlLoop() {
}

// We've broken out of the control loop due to error or admin shutdown request
log.fatal("BX-bot " + engineConfig.getBotId() + " is shutting down NOW!");
log.fatal("BX-bot {} is shutting down NOW!", engineConfig.getBotId());
synchronized (IS_RUNNING_MONITOR) {
isRunning = false;
}
Expand All @@ -205,23 +209,22 @@ private void runMainControlLoop() {
*/
void shutdown() {
log.info("Shutdown request received!");
log.info("Engine originally started in thread: " + engineThread);
log.info("Engine originally started in thread: {}", engineThread);
keepAlive = false;
engineThread.interrupt(); // poke it in case bot is sleeping
}

synchronized boolean isRunning() {
log.info("isRunning: " + isRunning);
log.info("isRunning: {}", isRunning);
return isRunning;
}

private void sleepUntilNextTradingCycle() {
log.info(
"*** Sleeping " + engineConfig.getTradeCycleInterval() + "s til next trade cycle... ***");
log.info("*** Sleeping {}s til next trade cycle... ***", engineConfig.getTradeCycleInterval());
try {
Thread.sleep(engineConfig.getTradeCycleInterval() * 1000L);
} catch (InterruptedException e) {
log.warn("Control Loop thread interrupted when sleeping before next trade cycle");
log.warn(THREAD_INTERRUPTED_WARN_MSG);
Thread.currentThread().interrupt();
}
}
Expand All @@ -241,7 +244,7 @@ private void handleExchangeNetworkException(ExchangeNetworkException e) {
try {
Thread.sleep(engineConfig.getTradeCycleInterval() * 1000L);
} catch (InterruptedException e1) {
log.warn("Control Loop thread interrupted when sleeping before next trade cycle");
log.warn(THREAD_INTERRUPTED_WARN_MSG);
Thread.currentThread().interrupt();
}
}
Expand Down Expand Up @@ -324,11 +327,11 @@ private boolean isEmergencyStopLimitBreached()

private ExchangeAdapter loadExchangeAdapter() {
final ExchangeConfig exchangeConfig = exchangeConfigService.getExchangeConfig();
log.info("Fetched Exchange config from repository: " + exchangeConfig);
log.info("Fetched Exchange config from repository: {}", exchangeConfig);

final ExchangeAdapter adapter =
configurableComponentFactory.createComponent(exchangeConfig.getAdapter());
log.info("Trading Engine will use Exchange Adapter for: " + adapter.getImplName());
log.info("Trading Engine will use Exchange Adapter for: {}", adapter.getImplName());

final ExchangeConfigImpl exchangeApiConfig =
ExchangeApiConfigBuilder.buildConfig(exchangeConfig);
Expand All @@ -338,15 +341,15 @@ private ExchangeAdapter loadExchangeAdapter() {

private EngineConfig loadEngineConfig() {
final EngineConfig loadedEngineConfig = engineConfigService.getEngineConfig();
log.info("Fetched Engine config from repository: " + loadedEngineConfig);
log.info("Fetched Engine config from repository: {}", loadedEngineConfig);
return loadedEngineConfig;
}

private List<TradingStrategy> loadTradingStrategies() {
final List<StrategyConfig> strategies = strategyConfigService.getAllStrategyConfig();
log.info("Fetched Strategy config from repository: " + strategies);
log.info("Fetched Strategy config from repository: {}", strategies);
final List<MarketConfig> markets = marketConfigService.getAllMarketConfig();
log.info("Fetched Markets config from repository: " + markets);
log.info("Fetched Markets config from repository: {}", markets);
return tradingStrategiesBuilder.buildStrategies(strategies, markets, exchangeAdapter);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -94,18 +94,19 @@ protected PasswordAuthentication getPasswordAuthentication() {
message.setSubject(subject);
message.setText(msgContent);

log.info("About to send following Email Alert with message content: " + msgContent);
log.info("About to send following Email Alert with message content: {}", msgContent);
Transport.send(message);

} catch (MessagingException e) {
log.error("Failed to send Email Alert. Details: " + e.getMessage(), e);
if (log.isErrorEnabled()) {
log.error("Failed to send Email Alert. Details: {}", e.getMessage(), e);
}
}
} else {
log.warn(
"Email Alerts are disabled. Not sending the following message: Subject: "
+ subject
+ " Content: "
+ msgContent);
"Email Alerts are disabled. Not sending the following message: Subject: {} Content: {}",
subject,
msgContent);
}
}

Expand All @@ -129,12 +130,12 @@ private void initialise() {
throw new IllegalStateException(errorMsg);
}

log.info("SMTP host: " + smtpConfig.getHost());
log.info("SMTP TLS Port: " + smtpConfig.getTlsPort());
log.info("Account username: " + smtpConfig.getAccountUsername());
log.info("SMTP host: {}", smtpConfig.getHost());
log.info("SMTP TLS Port: {}", smtpConfig.getTlsPort());
log.info("Account username: {}", smtpConfig.getAccountUsername());
// Account password not logged intentionally
log.info("From address: " + smtpConfig.getFromAddress());
log.info("To address: " + smtpConfig.getToAddress());
log.info("From address: {}", smtpConfig.getFromAddress());
log.info("To address: {}", smtpConfig.getToAddress());

smtpProps = new Properties();
smtpProps.put("mail.smtp.auth", "true");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public <T> T createComponent(String componentClassName) {
try {
final Class<?> componentClass = Class.forName(componentClassName);
final Object rawComponentObject = componentClass.getDeclaredConstructor().newInstance();
log.info("Successfully created the Component class for: " + componentClassName);
log.info("Successfully created the Component class for: {}", componentClassName);
return (T) rawComponentObject;

} catch (ClassNotFoundException
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,17 +108,14 @@ public static boolean isEmergencyStopLimitBreached(
} else {

log.info(
"Emergency Stop Currency balance available on exchange is ["
+ new DecimalFormat(DECIMAL_FORMAT_PATTERN).format(currentBalance)
+ "] "
+ engineConfig.getEmergencyStopCurrency());
"Emergency Stop Currency balance available on exchange is [{}] {}",
new DecimalFormat(DECIMAL_FORMAT_PATTERN).format(currentBalance),
engineConfig.getEmergencyStopCurrency());

log.info(
"Balance that will stop ALL trading across ALL markets is ["
+ new DecimalFormat(DECIMAL_FORMAT_PATTERN)
.format(engineConfig.getEmergencyStopBalance())
+ "] "
+ engineConfig.getEmergencyStopCurrency());
"Balance that will stop ALL trading across ALL markets is [{}] {}",
new DecimalFormat(DECIMAL_FORMAT_PATTERN).format(engineConfig.getEmergencyStopBalance()),
engineConfig.getEmergencyStopCurrency());

if (currentBalance.compareTo(engineConfig.getEmergencyStopBalance()) < 0) {
final String balanceBlownErrorMsg =
Expand Down

0 comments on commit 4b45b96

Please sign in to comment.