qos-ch / logback

The reliable, generic, fast and flexible logging framework for Java.
http://logback.qos.ch
Other
2.97k stars 1.28k forks source link

Expose copy of map of deques in LogbackMDCAdapter #795

Open alexanderjastram opened 5 months ago

alexanderjastram commented 5 months ago

Currently, only the regular property map is exposed in the MDCAdapter, and formatters such as the LogStashFormatter use the properties defined there to add additional tags to logs. This makes it impossible to have stack-based logger context, since children can potentially overwrite the context of their parents.

For example:

class LoggingExample {
  main() {
      MDC.put('key', 'valueParent');
      subMethod();
      log.info('parent log message');
  }

  subMethod() {
      MDC.put('key', 'valueChild');
      log.info('child log message');
  }

}

would result in the following logs:

> child log message key:valueChild
> parent log message key:valueChild

Now using the dequed properties we can keep track of the parent property instead of overwriting it:

class LoggingExample {
  main() {
      MDC.pushByKey('key', 'valueParent');
      subMethod();
      log.info('parentLog');
      MDC.popByKey('key')
  }

  subMethod() {
      MDC.pushByKey('key', 'valueChild');
      log.info('childLog');
      MDC.popByKey('key')
  }

}

Ideally this would result in the following logs:

> child log message key:valueChild
> parent log message key:valueParent

Unfortunately, the key value pairs of the dequeue map are not exposed, so the example above cannot be implemented. If it was exposed we could make a custom JSONProvider that provides the tags from the dequed map.

ceki commented 5 months ago

@alexanderjastram Thank you for this report. Could you please provide a patch or a PR?

alexanderjastram commented 5 months ago

will do - I'll post it here once its done

ceki commented 5 months ago

@alexanderjastram No need to provide a full implementation. Just the gist of the api you wish to see.

alexanderjastram commented 5 months ago

@ceki it requires 2 pull requests, since we also need to expose the copy in the ThreadLocalMapOfStacks: slf4j logback