Search code examples
javalogginglog4jmdc

MDC to differentiate logging between modules


My software uses a Service Oriented Architecture (SOA). All the services (lets call them modules for simplicity) writes to a single log file. I would like to distinguish logging between modules. Below is how I would like my log message to look like.

[MODULE-1] INFO - This is a test log message from MODULE ONE
[MODULE-2] INFO - This is a test log message from MODULE TWO

The advantage I see doing this is I would be able to grep necessary information while 'tail-ing' the logs. Also, while analyzing the logs, I can grep necessary module wise information. Is this achievable? I use log4j as my logging utility. Note that each modules can have multiple packages (hierarchy of packages). The closest I came across to achieve this is by using MDC.


Solution

  • I was able to achieve this by using MDC (MappedDiagnosticContext). Fortunately, my SOA framework allowed me a place where I could place my context information (service/module name) in a pretty generic way. Below is the code snipped which did it for me.

    MDC.put("MODULE", getServiceName())
    

    Ofcourse I was able to retrieve the information using -X tag in the EnhancedPatternLayout.