1

I have a multithreaded application where every thread operates different objects with names i.e.:

process-1
process-2
process-3

Currently the pattern looks like this:

[%thread] - %msg %n

And I want to achieve something like this:

[%thread] %processName - %msg %n

Where processName is specified in the object.

My goal is to add those names to generated logs, so I would be able to grep them very easily when I will need to review history. I'm logging already thread name, but this is not enough for me.

I have started with MDC, however, turns out it keeps the stored name between all threads. In the best scenario, it uses that name for all logs, in worst, the property is empty.

How can I achieve this thread-safe logging with or without MDC?

Forin
  • 1,549
  • 2
  • 20
  • 44
  • MDC values are thread local, I don't know what you mean with _it keeps the stored name between all threads_. Before Logback 1.1.5 an MDC context was automatically inherited by child threads. After 1.1.5 MDC contexts are no longer automatically inherited. – Robert Jan 11 '19 at 16:10
  • isn't it enough to log `processName` in `msg`? – nandsito Jan 11 '19 at 16:21
  • I think you are using a thread pool and you're not clearing the MDC values at the end of processing resulting in the same MDC value being printed for two different task. Note that MDC values are stored in `ThreadLocal` variables. Now since at the end of a task, the thread is returned to the pool for use by a different task, the MDC values stay. – Saptarshi Basu Jan 11 '19 at 16:30
  • @nandsito that means send processid as argument to every method – imperezivan Jan 11 '19 at 17:38
  • @SaptarshiBasu exactly. So I have to clean the ThreadLocal before the thread is returned to the pool? – Forin Jan 14 '19 at 09:46

1 Answers1

0

I suppose that each process run in different thread thus when start a thread put in MDC the id process

// this method runs in different thread for each invocation.
public void startProcess(String idProcess) {
    MDC.put("processName", idProcess);
     ....

and in your logback change the pattern

[%thread] %X{processName} %msg %n

the put method save the id in the thread, thus each thread will have different value

imperezivan
  • 761
  • 5
  • 13