Skip to content

Commit

Permalink
fix logging aspect
Browse files Browse the repository at this point in the history
  • Loading branch information
aomegax committed Feb 20, 2024
1 parent 7bb5b01 commit 7f92fe8
Show file tree
Hide file tree
Showing 3 changed files with 100 additions and 18 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package it.gov.pagopa.standinmanager.config;

import it.gov.pagopa.standinmanager.model.ProblemJson;
import it.gov.pagopa.standinmanager.exception.AppError;
import jakarta.annotation.PostConstruct;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.stream.StreamSupport;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Expand All @@ -12,6 +17,7 @@
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.CodeSignature;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
Expand All @@ -24,6 +30,8 @@
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import static it.gov.pagopa.standinmanager.util.Util.deNull;

@Aspect
@Component
@Slf4j
Expand All @@ -34,6 +42,11 @@ public class LoggingAspect {
public static final String STATUS = "status";
public static final String CODE = "httpCode";
public static final String RESPONSE_TIME = "responseTime";
public static final String FAULT_CODE = "faultCode";
public static final String FAULT_DETAIL = "faultDetail";
public static final String REQUEST_ID = "requestId";
public static final String OPERATION_ID = "operationId";
public static final String ARGS = "args";

@Autowired HttpServletRequest httRequest;

Expand All @@ -48,15 +61,6 @@ public class LoggingAspect {
@Value("${info.properties.environment}")
private String environment;

private static String getExecutionTime() {
String startTime = MDC.get(START_TIME);
if (startTime != null) {
long endTime = System.currentTimeMillis();
long executionTime = endTime - Long.parseLong(startTime);
return String.valueOf(executionTime);
}
return "1";
}

@Pointcut("@within(org.springframework.web.bind.annotation.RestController)")
public void restController() {
Expand Down Expand Up @@ -109,11 +113,18 @@ public void handleContextRefresh(ContextRefreshedEvent event) {
public Object logApiInvocation(ProceedingJoinPoint joinPoint) throws Throwable {
MDC.put(METHOD, joinPoint.getSignature().getName());
MDC.put(START_TIME, String.valueOf(System.currentTimeMillis()));
log.info("{} {}", httRequest.getMethod(), httRequest.getRequestURI());
MDC.put(OPERATION_ID, UUID.randomUUID().toString());
if(MDC.get(REQUEST_ID) == null) {
var requestId = UUID.randomUUID().toString();
MDC.put(REQUEST_ID, requestId);
}
Map<String, String> params = getParams(joinPoint);
MDC.put(ARGS, params.toString());

log.info(
"Invoking API operation {} - args: {}",
joinPoint.getSignature().getName(),
joinPoint.getArgs());
params);

Object result = joinPoint.proceed();

Expand All @@ -130,23 +141,56 @@ public Object logApiInvocation(ProceedingJoinPoint joinPoint) throws Throwable {
}

@AfterReturning(value = "execution(* *..exception.ErrorHandler.*(..))", returning = "result")
public void trowingApiInvocation(JoinPoint joinPoint, ResponseEntity<?> result) {
public void trowingApiInvocation(JoinPoint joinPoint, ResponseEntity<ProblemJson> result) {
MDC.put(STATUS, "KO");
MDC.put(CODE, String.valueOf(result.getStatusCodeValue()));
MDC.put(RESPONSE_TIME, getExecutionTime());
MDC.put(FAULT_CODE, getTitle(result));
MDC.put(FAULT_DETAIL, getDetail(result));
log.info("Failed API operation {} - error: {}", MDC.get(METHOD), result);
MDC.remove(STATUS);
MDC.remove(CODE);
MDC.remove(RESPONSE_TIME);
MDC.remove(START_TIME);
MDC.clear();
}

@Around(value = "repository() || service()")
public Object logTrace(ProceedingJoinPoint joinPoint) throws Throwable {
Map<String, String> params = getParams(joinPoint);
log.debug(
"Call method {} - args: {}", joinPoint.getSignature().toShortString(), joinPoint.getArgs());
"Call method {} - args: {}", joinPoint.getSignature().toShortString(), params);
Object result = joinPoint.proceed();
log.debug("Return method {} - result: {}", joinPoint.getSignature().toShortString(), result);
return result;
}

private static String getDetail(ResponseEntity<ProblemJson> result) {
if(result != null && result.getBody() != null && result.getBody().getDetail() != null) {
return result.getBody().getDetail();
} else return AppError.UNKNOWN.getDetails();
}

private static String getTitle(ResponseEntity<ProblemJson> result) {
if(result != null && result.getBody() != null && result.getBody().getTitle() != null) {
return result.getBody().getTitle();
} else return AppError.UNKNOWN.getTitle();
}

private static String getExecutionTime() {
String startTime = MDC.get(START_TIME);
if (startTime != null) {
long endTime = System.currentTimeMillis();
long executionTime = endTime - Long.parseLong(startTime);
return String.valueOf(executionTime);
}
return "-";
}

private static Map<String, String> getParams(ProceedingJoinPoint joinPoint) {
CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();
Map<String, String> params = new HashMap<>();
int i = 0;
for (var paramName : codeSignature.getParameterNames()) {
params.put(paramName, deNull(joinPoint.getArgs()[i++]));
}
return params;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
@Getter
public enum AppError {
INTERNAL_SERVER_ERROR(
HttpStatus.INTERNAL_SERVER_ERROR, "Internal Server Error", "Something was wrong");
HttpStatus.INTERNAL_SERVER_ERROR, "Internal Server Error", "Something was wrong"),
UNKNOWN(null, null, null);

public final HttpStatus httpStatus;
public final String title;
Expand Down
37 changes: 37 additions & 0 deletions src/main/java/it/gov/pagopa/standinmanager/util/Util.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package it.gov.pagopa.standinmanager.util;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

public class Util {

public static String format(LocalDate d) {
return d.format(DateTimeFormatter.ISO_DATE);
}

/**
* @param value value to deNullify.
* @return return empty string if value is null
*/
public static String deNull(String value) {
return Optional.ofNullable(value).orElse("");
}

/**
* @param value value to deNullify.
* @return return empty string if value is null
*/
public static String deNull(Object value) {
return Optional.ofNullable(value).orElse("").toString();
}

/**
* @param value value to deNullify.
* @return return false if value is null
*/
public static Boolean deNull(Boolean value) {
return Optional.ofNullable(value).orElse(false);
}

}

0 comments on commit 7f92fe8

Please sign in to comment.