0

I would like to log in multitenant (Java Spring with Akka) application. Each logline should contain the tenant id, I found that the MDC looks perfect for this purpose. I use akka.event.Logging for actors, and SLF4J (org.slf4j.Logger) for other parts of the code. I am quite new with MDC and AspectJ.

example:

logger.info("Tenant: {} is processed", tenantId);

I would like to run the following code before every log lines creation which contains tenantId variable name (like the example):

@Aspect
public class MDCUtils {

    /**
     *  Set TenantId on MDC context map
     *
     * @param tenantId
     */
    @Before(???)
    public static void setTenantId(String tenantId) {
        Map<String, String> contextMap = new HashMap<>();
        contextMap.put("tenantId", tenantId);
        MDC.setContextMap(contextMap);
    }
}

What should I put inside the @Before() to catch all of log lines creation which contains tenantId variable name. If I catched them, how can I retrieve the tenantId value? (Most of these loglines have more than one parameter, not only tenantId)

I would like to use tenantId for this pattern:

<pattern>%X{tenant} %d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n</pattern>
Xi Tan
  • 63
  • 9
user2695543
  • 81
  • 4
  • 22
  • This is not how MDC works. Maybe you want to read [this tutorial](http://www.baeldung.com/mdc-in-log4j-2-logback). If you are already logging the tenant ID manually anyway, why do you want to put it into MDC to be logged a second time via formatting pattern? What do you really want to achieve instead? Maybe refactor the application so as to replace manual logging by logging via aspect? Or log the tenant ID in other log messages where it is **not** logged manually at the moment? – kriegaex Mar 08 '18 at 13:54
  • 1
    _(continued)_ BTW, you should not try to extract the ID from log messages but from a method or constructor call actually using the ID as a parameter. Sorry, but your question is really unclear. Like so many others you are making the mistake not to describe **what** you want to achieve and not to show the existing code you want to change or enhance. Instead you describe **how** you believe the problem should be solved, but without knowing. Nobody can solve your problem by seeing an imaginary solution. Make us see the problem and let someone suggest a solution. – kriegaex Mar 08 '18 at 13:56

0 Answers0