Apache logging services logo Apache log4j logo

Log4j 2 API


One of the primary purpose of a logging framework is to provide the means to generate debugging and diagnostic information only when it is needed, and to allow filtering of that information so that it does not overwhelm the system or the individuals who need to make use of it. As an example, an application desires to log its entry, exit and other operations separately from SQL statements being executed, and wishes to be able to log queries separate from updates. One way to accomplish this is shown below:

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import java.util.Map;

public class MyApp {

    private Logger logger = LogManager.getLogger(MyApp.class.getName());
    private static final Marker SQL_MARKER = MarkerManager.getMarker("SQL");
    private static final Marker UPDATE_MARKER = MarkerManager.getMarker("SQL_UPDATE", SQL_MARKER);
    private static final Marker QUERY_MARKER = MarkerManager.getMarker("SQL_QUERY", SQL_MARKER);

    public String doQuery(String table) {

        logger.debug(QUERY_MARKER, "SELECT * FROM {}", table);

        return logger.exit();

    public String doUpdate(String table, Map<String, String> params) {

        if (logger.isDebugEnabled()) {
          logger.debug(UPDATE_MARKER, "UPDATE {} SET {}", table, formatCols());

        return logger.exit();

    private String formatCols(Map<String, String> cols) {
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> entry : cols.entrySet()) {
            if (!first) {
                sb.append(", ");
            first = false;
        return sb.toString();

In the example above it is now possible to add MarkerFilters to only allow SQL update operations to be logged, all SQL updates to be logged or to log everything in MyApp.

Some important rules about Markers must be considered when using them.

  1. Markers must be unique. They are permanently registered by name so care should be taken to insure that Markers used in your application are distinct from those in the application's dependencies, unless that is what is desired.
  2. Like many objects in Log4j 2, Markers are immutable. If a marker has a parent, the parent must be named when the Marker is created and the parent cannot be changed after creation.
  3. Markers only have a single parent. Markers can, however, have many children that reference them.