Small question regarding MDC with Java please.
At first, I had very straightforward methods, some methods with many parameters (I shorten the list of parameters to keep things short just for this question, but please imagine a lot of parameters)
public String invokeMethodForPerson(int age, String name, boolean isCool, long distanceRun, double weight) {
LOGGER.info("begin to invoke method invokeMethodForPerson");
return methodForPerson(age, name, isCool, distanceRun, weight);
}
public String invokeMethodForCar(String model, boolean isElectric, long price, int numberOfDoors) {
LOGGER.info("begin to invoke method invokeMethodForCar");
return methodForCar(model, isElectric, price, numberOfDoors);
}
public String invokeMethodForFlower(String name, String color) {
LOGGER.info("begin to invoke method invokeMethodForFlower");
return methodForFlower(name, color);
}
(This question is not about how to refactor the long list of parameters)
Then, I wanted to leverage MDC. MDC is very helpful, it allow better search in log aggregator tools etc. Having them as first level, not inside the logger itself is very helpful.
Therefore, in order to leverage MDC, the code went from simple, to something now similar to this, here is what I tried.
public String invokeMethodForPerson(int age, String name, boolean isCool, long distanceRun, double weight) {
MDC.put("age", age);
MDC.put("name", name);
MDC.put("isCool", isCool);
MDC.put("distanceRun", distanceRun);
MDC.put("weight", weight);
LOGGER.info("begin to invoke method invokeMethodForPerson");
return methodForPerson(age, name, isCool, distanceRun, weight);
}
public String invokeMethodForCar(String model, boolean isElectric, long price, int numberOfDoors) {
MDC.put("model", model);
MDC.put("isElectric", isElectric);
MDC.put("price", price);
MDC.put("numberOfDoors", numberOfDoors);
LOGGER.info("begin to invoke method invokeMethodForCar");
return methodForCar(model, isElectric, price, numberOfDoors);
}
public String invokeMethodForFlower(String name, String color) {
MDC.put("name", name);
MDC.put("color", color);
LOGGER.info("begin to invoke method invokeMethodForFlower");
return methodForFlower(name, color);
}
Problem: now looking at the code, there is actually more lines of MDC.put()
than actual business logic code
Question: Is there a cleaner way to leveraging MDC, for many parameters, other than just adding tons of lines of MDC.put()
, if possible, using AOP/aspects/advice/pointcut please?
Thank you