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

gavenkoa picture gavenkoa · May 29, 2013 · Viewed 61.6k times · Source

First time I hear about markers when read:

http://slf4j.org/faq.html

I check available methods for Logger object:

and found interfaces:

More in-depth info I get from:

but still confused... Note that I ask why, not how to use them, so this is not a duplicate of:

UPDATE Seems that when you use markers you also required to write custom Java code instead doing configuration in XML or .property files...

UPDATE 2 From http://logback.qos.ch/manual/appenders.html#OnMarkerEvaluator

Marker notifyAdmin = MarkerFactory.getMarker("NOTIFY_ADMIN");
logger.error(notifyAdmin,
  "This is a serious an error requiring the admin's attention",
   new Exception("Just testing"));

Answer

Ceki picture Ceki · May 29, 2013

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.