Java - Log4j

Java Conceptuel Diagram


Log4j is a debugging logger.


  • 1.2 (2015 switch to 2.x)
  • 2


dependencies {
    compile 'org.apache.logging.log4j:log4j-api:2.13.0'
    compile 'org.apache.logging.log4j:log4j-core:2.13.0'


Get a logger

  • The name of this Logger will be the full qualified class name or where it reside. If the class is located at “”, the name will be the same
protected static final Logger parentLogger = LogManager.getLogger();



markers (log4j.Marker class) are objects that are used to add easily filterable information to log messages. Markers can be hierarchical - each Marker may have a parent. This allows for broad categories being subdivided into more specific categories. An example might be a Marker named “Error” with children named “SystemError” and “ApplicationError”.

Markers must be unique.

// A parent
Marker SQL_MARKER = MarkerManager.getMarker("SQL");
// A query marker
Marker QUERY_MARKER = MarkerManager.getMarker("SQL_QUERY").setParents(SQL_MARKER);
// A debug message with a marker
logger.debug(QUERY_MARKER, "SELECT * FROM {}", table);



By default, Log4j looks for a configuration file named log4j2.xml (not log4j.xml) in the classpath.

The order on how log4j search the configuration can be found in the AutomaticConfiguration section

  • First via a java property:


Format supported:

  • properties
  • xml
  • yaml



The default configuration xml would look like that.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    <Root level="error">
      <AppenderRef ref="Console"/>


public class Main

    private final static Logger logger = Logger.getLogger(Main.class);

    public static void main(final String[] args) throws Exception
        // Minimal Configuration

        if (args.length != 1)
            logger.error("Please provide an argument");


How to dynamically create different log file

see Log4j - How to route message to log file created dynamically

Multiple Thread Programmatic

A constructor code where the logger is declared as class variable private Logger threadLogger

// Logger Name is normally hierarchic ""
// We add the thread name
String loggerName = QueryExecutor.class.getCanonicalName()+"."+threadName;
LOGGER = Logger.getLogger(loggerName);

// Log4j properties
Properties log4jProp = new Properties();

// Once a message is accepted by the logger,
// it's sent to one or several appenders (to a file, to the console, to a mail server, etc.).
final String appenderName = "FileAppender";
// Set logger level to DEBUG and its only appender.
log4jProp.setProperty("log4j.logger."+loggerName, "DEBUG, " + appenderName);

// File Appender
log4jProp.setProperty("log4j.appender." + appenderName,"org.apache.log4j.FileAppender");
// Properties are the set method (File equivalent to setFile)
String timeStamp = new SimpleDateFormat("").format(new Date());
String logFileName = loggerName+"_"+timeStamp+".log";
log4jProp.setProperty("log4j.appender." + appenderName + ".File", logFileName);
// Above Warning
// The levels of logging are TRACE, DEBUG, INFO, WARN, ERROR and FATAL.
// See org.apache.log4j.Level
log4jProp.setProperty("log4j.appender." + appenderName + ".Threshold","WARN");
// Layout is org.apache.log4j.PatternLayout
log4jProp.setProperty("log4j.appender." + appenderName + ".layout","org.apache.log4j.PatternLayout");
// See org.apache.log4j.PatternLayout#setConversionPattern date in ISO 8601 format, thread name, level, logger, message
log4jProp.setProperty("log4j.appender." + appenderName + ".layout.ConversionPattern","%d [%t] %-5p %c - %m%n");


Dynamic with Builder

Note that a rolling file appender added this way cannot use lookup value

RollingFileAppender rollingFileAppender = RollingFileAppender.newBuilder()
      .setName("analytics-" + contextEventFileNameExpression)
         * It causes a rollover once the date/time pattern no longer applies to the active file.

Discover More
Java Conceptuel Diagram
How to configure Log4J programmatically in two steps?

This article shows you how to configure Log4j 2.2 programmatically by extending the actual configuration. Because Log4J gives the possibility to reload a configuration file. If this were the case, the...
Java Conceptuel Diagram
Java - (Debugging) Logger, Logging system

in Java. A configuration provide specifications for: Logger objects - A Logger is the entry point to logs messages. Appenders (or Handlers) define where to write the message (console stdout,...
Java Conceptuel Diagram
Java - Logger

A Logger is the entry point to logs messages. The main entity on which applications make logging calls. A Logger object is used to log messages. It has a hierarchical scope that is generally the...
Java Conceptuel Diagram
Java - Slf4j

slf4j ) is a façade for loggers. To use a specific logger, add one of the binding logger package. Library should declare a runtime dependency only on on slf4j-api and not on any SLF4J binding but...
Java Conceptuel Diagram
Java Logging - Message (or record)

Each level corresponds to a numeric value. Log4J2: fatal, error, warning, info, debug, Trace : Finest, Finer, Fine, Config, Info, Warning, Severe
Data System Architecture
Log - Logging

A log is a text file with: a timed list of message (activities) that an application has performed execution/request log: web server: web log ( - that stores the Http request error cron...
Java Conceptuel Diagram
Log4j - How to route message to log file created dynamically

How to route message to file created dynamically. This is already embedded in the core log4j functionality when you combine: RoutingAppender...
Data System Architecture

LogStash is: * a metrics collector * a log collector. * with pipeline ability A Logstash pipeline is composed of the following elements; * input (produce the data) * filter (optional, process...
Java Conceptuel Diagram
Logging - Context (Mapped Diagnostic Context)

Context data (also known as Mapped Diagnostic Context or MDC) To be able to follow a request that flow in different component, you need to put the request ID in every message (generally a GUID. It's...
Java Conceptuel Diagram
Logging - Logger Manager | Logger Factory

Logging - Logger Manager | Logger Factory A static logger factory is the entry point to get/create/retrieve a logger Logger Manager manages the loggers and its hierarchical namespace (ie if a logger...

Share this page:
Follow us:
Task Runner