What are markers in Java Logging frameworks and what is a reason to use them?

77,191

This is a rehashed version my answer to the question "Best practices for using Markers in SLF4J/Logback".

Markers can be used to color or mark a single log statement. What you do with these colors, i.e. markers, is entirely up to you. However, two patterns seem to be common for marker usage.

  1. Triggering: Some appender could be instructed to take an action in the presence of a certain marker. For example, SMTPAppender can be configured to send an email whenever a logging event is marked with the NOTIFY_ADMIN marker regardless of the log level. See marker-based triggering in the logback documentation. You may also combine log levels and markers for triggering.

  2. Filtering: Markers are very useful for making certain valuable log statements stand out. For example, you can color/mark all your persistence related logs (in various and multiple class files) with the color "DB". You could then filter for "DB": disable logging except for log statements marked with DB. See the chapter on filters in the logback documentation for more information (search for MarkerFilter). Note that filtering on markers can be performed not just by logback but log analysis tools as well.

Before the advent of Markers, to achieve similar behavior, you had the option 1) using custom levels 2) use modified logger names. SLF4J API currently does not support custom levels. As for option 2, suffixing (or prefixing) logger names is workable if a one or two loggers need to be modified. The approach becomes impractical as soon 3 or more loggers need to be "sub-classed" because the associated configuration files become unmanageable.

Even though a single marker can be already very useful, the next version of SLF4J, i.e. version 2.0, will allow multiple markers per log statement.

Share:
77,191
gavenkoa
Author by

gavenkoa

Software developer and instructor. Mathematician by education. Daily use Emacs and Firefox under Debian )) Visit my home page: http://defun.work/ Resume: http://resume.defun.work/ Blog: http://blog.defun.work/ IT Tips: http://tips.defun.work/ Public source code: http://hg.defun.work/

Updated on July 08, 2022

Comments