Skip to content

Commit

Permalink
added logging to the contracts microservice
Browse files Browse the repository at this point in the history
  • Loading branch information
Kemosalamy committed May 15, 2024
1 parent e436f0f commit bb4c778
Show file tree
Hide file tree
Showing 18 changed files with 160 additions and 51 deletions.
8 changes: 8 additions & 0 deletions services/contracts/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>com.workup</groupId>
<artifactId>shared</artifactId>
Expand Down Expand Up @@ -86,6 +90,10 @@
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import static com.workup.contracts.tests.InitiateContractTests.initiateContractTest1;

import com.workup.contracts.logger.ContractsLogger;
import com.workup.contracts.logger.LoggingLevel;
import com.workup.shared.enums.ServiceQueueNames;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Queue;
Expand All @@ -26,7 +28,7 @@ public static void main(String[] args) {
@Bean
public ApplicationRunner runner(AmqpTemplate template) {
return args -> {
System.out.println("ApplicationRunner is executing");
ContractsLogger.print("ApplicationRunner is executing", LoggingLevel.TRACE);

// Use below example function to test sending to the queue.
initiateContractTest1(template);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.workup.contracts;

import com.workup.contracts.commands.*;
import com.workup.contracts.logger.ContractsLogger;
import com.workup.contracts.logger.LoggingLevel;
import com.workup.shared.commands.contracts.requests.ContractTerminationRequest;
import com.workup.shared.commands.contracts.requests.EvaluateMilestoneRequest;
import com.workup.shared.commands.contracts.requests.GetContractRequest;
Expand Down Expand Up @@ -63,7 +65,7 @@ public ViewContractMilestonesResponse receive(ViewContractMilestonesRequest in)

@RabbitHandler
public GetContractResponse receive(GetContractRequest in) throws Exception {
System.out.println("** ENTERED GET CONTRACT RABBITMQ");
ContractsLogger.print("** ENTERED GET CONTRACT RABBITMQ", LoggingLevel.TRACE);
return ((GetContractCommand) commandMap.getCommand("GetContract")).Run(in);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.workup.contracts.commands;

import com.workup.contracts.logger.ContractsLogger;
import com.workup.contracts.logger.LoggingLevel;
import com.workup.contracts.models.Contract;
import com.workup.contracts.models.ContractMilestone;
import com.workup.shared.commands.contracts.requests.EvaluateMilestoneRequest;
Expand Down Expand Up @@ -42,10 +43,10 @@ public EvaluateMilestoneResponse Run(EvaluateMilestoneRequest request) {

try {
contractMilestoneRepository.save(updatedMilestone);
ContractsLogger.print(" [x] Milestone evaluated " + updatedMilestone);
ContractsLogger.print(" [x] Milestone evaluated " + updatedMilestone, LoggingLevel.TRACE);

if (request.getEvaluatedState() == MilestoneState.ACCEPTED) {
ContractsLogger.print(" [x] Sending payment request ");
ContractsLogger.print(" [x] Sending payment request ", LoggingLevel.TRACE);
// Getting the contract as we need to send the freelancer and client id since they are
// in the payment request parameters.
Optional<Contract> contractOptional =
Expand All @@ -63,7 +64,7 @@ public EvaluateMilestoneResponse Run(EvaluateMilestoneRequest request) {
.withDescription(updatedMilestone.getMilestoneId().toString())
.build();
rabbitTemplate.convertSendAndReceive(ServiceQueueNames.PAYMENTS, externalRequest);
ContractsLogger.print(" [x] Payment request sent ");
ContractsLogger.print(" [x] Payment request sent ", LoggingLevel.TRACE);
}

return EvaluateMilestoneResponse.builder()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.workup.contracts.commands;

import com.workup.contracts.logger.ContractsLogger;
import com.workup.contracts.logger.LoggingLevel;
import com.workup.contracts.models.Contract;
import com.workup.shared.commands.contracts.requests.GetContractRequest;
import com.workup.shared.commands.contracts.responses.GetContractResponse;
Expand All @@ -18,7 +19,8 @@ public GetContractResponse Run(GetContractRequest request) {
(GetContractResponse) redisService.getValue(cachingKey, GetContractResponse.class);
if (cachedResponse != null) {
ContractsLogger.print(
"[x] Contract request response fetched from cache: " + cachedResponse.toString());
"[x] Contract request response fetched from cache: " + cachedResponse.toString(),
LoggingLevel.TRACE);

return cachedResponse;
}
Expand Down Expand Up @@ -52,7 +54,8 @@ public GetContractResponse Run(GetContractRequest request) {
redisService.setValue(cachingKey, response);
return response;
} catch (Exception ex) {
ContractsLogger.print("[x] Error occurred while fetching contract: " + ex.getMessage());
ContractsLogger.print(
"[x] Error occurred while fetching contract: " + ex.getMessage(), LoggingLevel.TRACE);
ex.printStackTrace();
return GetContractResponse.builder()
.withStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.workup.contracts.commands;

import com.workup.contracts.logger.ContractsLogger;
import com.workup.contracts.logger.LoggingLevel;
import com.workup.contracts.models.ContractMilestone;
import com.workup.shared.commands.contracts.requests.GetMilestoneRequest;
import com.workup.shared.commands.contracts.responses.GetMilestoneResponse;
Expand All @@ -19,7 +20,8 @@ public GetMilestoneResponse Run(GetMilestoneRequest request) {
(GetMilestoneResponse) redisService.getValue(cachingKey, GetMilestoneResponse.class);
if (cachedResponse != null) {
ContractsLogger.print(
"[x] Milestone request response fetched from cache: " + cachedResponse.toString());
"[x] Milestone request response fetched from cache: " + cachedResponse.toString(),
LoggingLevel.TRACE);

return cachedResponse;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.workup.contracts.commands;

import com.workup.contracts.logger.ContractsLogger;
import com.workup.contracts.logger.LoggingLevel;
import com.workup.contracts.models.TerminationRequest;
import com.workup.shared.commands.contracts.requests.GetPendingTerminationsRequest;
import com.workup.shared.commands.contracts.responses.GetPendingTerminationsResponse;
Expand All @@ -19,7 +20,8 @@ public GetPendingTerminationsResponse Run(GetPendingTerminationsRequest request)
redisService.getValue(cachingKey, GetPendingTerminationsResponse.class);
if (cachedResponse != null) {
ContractsLogger.print(
"[x] Contract terminations response fetched from cache: " + cachedResponse.toString());
"[x] Contract terminations response fetched from cache: " + cachedResponse.toString(),
LoggingLevel.TRACE);

return cachedResponse;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.workup.contracts.commands;

import com.workup.contracts.logger.ContractsLogger;
import com.workup.contracts.logger.LoggingLevel;
import com.workup.contracts.models.Contract;
import com.workup.contracts.models.TerminationRequest;
import com.workup.shared.commands.contracts.requests.HandleTerminationRequest;
Expand Down Expand Up @@ -42,7 +43,8 @@ private HandleTerminationResponse handleTerminationRequest(
}
try {
TerminationRequest updatedRequest = terminationRequestRepository.save(terminationRequest);
ContractsLogger.print(" [x] Updated Termination Request " + updatedRequest);
ContractsLogger.print(
" [x] Updated Termination Request " + updatedRequest, LoggingLevel.TRACE);
return HandleTerminationResponse.builder()
.withRequestStatus(updatedRequest.getStatus())
.withStatusCode(HttpStatusCode.OK)
Expand All @@ -68,7 +70,8 @@ private HandleTerminationResponse terminateContract(String contractId) {
updatedContract.setStatus(ContractState.TERMINATED);
try {
updatedContract = contractRepository.save(updatedContract);
ContractsLogger.print(" [x] Updated Contract Status to Terminated " + updatedContract);
ContractsLogger.print(
" [x] Updated Contract Status to Terminated " + updatedContract, LoggingLevel.TRACE);
} catch (Exception e) {
e.printStackTrace();
return HandleTerminationResponse.builder()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.workup.contracts.commands;

import com.workup.contracts.logger.ContractsLogger;
import com.workup.contracts.logger.LoggingLevel;
import com.workup.contracts.models.Contract;
import com.workup.contracts.models.ContractMilestone;
import com.workup.shared.commands.contracts.Milestone;
Expand Down Expand Up @@ -59,11 +60,13 @@ public InitiateContractResponse Run(InitiateContractRequest request) {
try {
Contract savedContract = contractRepository.save(contract);

ContractsLogger.print(" [x] Saved Contract '" + savedContract.getJobTitle());
ContractsLogger.print(
" [x] Saved Contract '" + savedContract.getJobTitle(), LoggingLevel.TRACE);

contractMilestoneRepository.saveAll(milestonesToAdd);

ContractsLogger.print(" [x] Saved All Milestones '" + savedContract.getJobTitle());
ContractsLogger.print(
" [x] Saved All Milestones '" + savedContract.getJobTitle(), LoggingLevel.TRACE);

return InitiateContractResponse.builder()
.withContractId(savedContract.getContractId().toString())
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.workup.contracts.commands;

import com.workup.contracts.logger.ContractsLogger;
import com.workup.contracts.logger.LoggingLevel;
import com.workup.contracts.models.ContractMilestone;
import com.workup.shared.commands.contracts.requests.MarkPaymentCompletedRequest;
import com.workup.shared.commands.contracts.responses.MarkPaymentCompletedResponse;
Expand Down Expand Up @@ -38,7 +40,8 @@ public MarkPaymentCompletedResponse Run(MarkPaymentCompletedRequest request) {

try {
contractMilestoneRepository.save(updatedMilestone);
System.out.println(" [x] Marked Milestone as Paid '" + updatedMilestone);
ContractsLogger.print(
" [x] Marked Milestone as Paid '" + updatedMilestone, LoggingLevel.TRACE);
return MarkPaymentCompletedResponse.builder().withStatusCode(HttpStatusCode.OK).build();
} catch (Exception e) {
e.printStackTrace();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.workup.contracts.commands;

import com.workup.contracts.logger.ContractsLogger;
import com.workup.contracts.logger.LoggingLevel;
import com.workup.contracts.models.ContractMilestone;
import com.workup.shared.commands.contracts.requests.ProgressMilestoneRequest;
import com.workup.shared.commands.contracts.responses.ProgressMilestoneResponse;
Expand Down Expand Up @@ -42,7 +43,7 @@ public ProgressMilestoneResponse Run(ProgressMilestoneRequest request) {

try {
contractMilestoneRepository.save(updatedMilestone);
ContractsLogger.print(" [x] Milestone Progressed " + updatedMilestone);
ContractsLogger.print(" [x] Milestone Progressed " + updatedMilestone, LoggingLevel.TRACE);
return ProgressMilestoneResponse.builder()
.withStatusCode(HttpStatusCode.OK)
.withErrorMessage("")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.workup.contracts.commands;

import com.workup.contracts.logger.ContractsLogger;
import com.workup.contracts.logger.LoggingLevel;
import com.workup.contracts.models.Contract;
import com.workup.contracts.models.TerminationRequest;
import com.workup.shared.commands.contracts.requests.ContractTerminationRequest;
Expand Down Expand Up @@ -69,7 +70,7 @@ public ContractTerminationResponse Run(ContractTerminationRequest request) {
try {
TerminationRequest savedRequest = terminationRequestRepository.save(terminationRequest);

ContractsLogger.print(" [x] Saved Termination Request '" + savedRequest);
ContractsLogger.print(" [x] Saved Termination Request '" + savedRequest, LoggingLevel.TRACE);

return ContractTerminationResponse.builder()
.withRequestId(savedRequest.getRequestId().toString())
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
package com.workup.contracts.logger;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator;

public class ContractsLogger {
private static final Logger logger = LogManager.getLogger(ContractsLogger.class);

public static void print(String logMessage, LoggingLevel level) {
Configurator.setRootLevel(Level.ERROR);

public static void print(String logMessage) {
System.out.println(logMessage);
switch (level) {
case TRACE -> logger.trace("Trace level log message: " + logMessage);
case DEBUG -> logger.debug("Debug level log message: " + logMessage);
case INFO -> logger.info("Info level log message: " + logMessage);
case WARN -> logger.warn("Warn level log message: " + logMessage);
case ERROR -> logger.error("Error level log message: " + logMessage);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.workup.contracts.logger;

public enum LoggingLevel {
TRACE,
DEBUG,
INFO,
WARN,
ERROR
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.workup.contracts.tests;

import com.workup.contracts.logger.ContractsLogger;
import com.workup.contracts.logger.LoggingLevel;
import com.workup.shared.commands.contracts.Milestone;
import com.workup.shared.commands.contracts.requests.InitiateContractRequest;
import com.workup.shared.commands.contracts.responses.InitiateContractResponse;
Expand All @@ -13,7 +15,7 @@
public class InitiateContractTests {

public static void initiateContractTest1(AmqpTemplate template) throws ParseException {
System.out.println("[ ] Running InitiateContractTest1...");
ContractsLogger.print("[ ] Running InitiateContractTest1...", LoggingLevel.TRACE);

Milestone milestone =
Milestone.builder()
Expand All @@ -39,8 +41,9 @@ public static void initiateContractTest1(AmqpTemplate template) throws ParseExce
template.convertSendAndReceive(ServiceQueueNames.CONTRACTS, initiateContractRequest);

assert resp != null : "InitiateContractTest1 Response was null";
System.out.println(
"Response success output: " + resp.getStatusCode() + " " + resp.getErrorMessage());
System.out.println("[x] Finished InitiateContractTest1...");
ContractsLogger.print(
"Response success output: " + resp.getStatusCode() + " " + resp.getErrorMessage(),
LoggingLevel.TRACE);
ContractsLogger.print("[x] Finished InitiateContractTest1...", LoggingLevel.TRACE);
}
}
4 changes: 3 additions & 1 deletion services/contracts/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ spring.cassandra.schema-action=CREATE_IF_NOT_EXISTS
spring.cache.type=redis
spring.cache.host=service_redis
spring.cache.port=6379
spring.cache.redis.time-to-live=600000
spring.cache.redis.time-to-live=600000

logging.level.root=INFO
52 changes: 52 additions & 0 deletions services/contracts/src/main/resources/log4j2.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<Configuration>
<Properties>
<Property name="baseDir">logs/contracts</Property>
</Properties>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n"/>
</Console>

<RollingFile name="AppLogsFileAppender" fileName="${baseDir}/app.log"
filePattern="${baseDir}/app/%d{yyyy}/%d{MM}/%d{dd}/%d{HH:mm:ss}.log.gz">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
<Policies>
<!-- Time-based policy: Rolls daily at midnight -->
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
<!-- Size-based policy: Rolls after the log file reaches 10 MB -->
<SizeBasedTriggeringPolicy size="10 MB"/>
</Policies>
<DefaultRolloverStrategy max="30">
<Delete basePath="${baseDir}/app" maxDepth="4">
<IfFileName glob="/app-.log.gz"/>
<IfLastModified age="30d"/>
</Delete>
</DefaultRolloverStrategy>
<Filters>
<!-- Deny ERROR to avoid duplication in AppLogs -->
<ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="NEUTRAL"/>
</Filters>
</RollingFile>

<RollingFile name="ErrorsLogsFileAppender" fileName="${baseDir}/errors.log"
filePattern="${baseDir}/errors/%d{yyyy}/%d{MM}/%d{dd}/%d{HH:mm:ss}.log.gz">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
<Policies>
<!-- Time-based policy: Rolls daily at midnight -->
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
<!-- Size-based policy: Rolls after the log file reaches 10 MB -->
<SizeBasedTriggeringPolicy size="10 MB"/>
</Policies>
</RollingFile>


</Appenders>

<Loggers>
<Root level="INFO">
<AppenderRef ref="Console" level="DEBUG"/>
<AppenderRef ref="AppLogsFileAppender"/>
<AppenderRef ref="ErrorsLogsFileAppender" level="ERROR"/>
</Root>
</Loggers>
</Configuration>
Loading

0 comments on commit bb4c778

Please sign in to comment.