[JAVA] Understand the basic mechanism of log4j2.xml

Motivation, premise, etc.

――Every time I touched log4j for the first time in a while, I completely forgot how to use it, so I decided to understand the structure in my own way. ――Because it was a great opportunity, I wanted to understand the basic structure first, so I basically specify options as much as possible. ――In addition, since it is limited to basic usage, settings that are often used in actual development are sometimes cut off.

Environment used

Java source to output logs


0. Without configuration file

--Even if there is no configuration file, log output will be performed with the default settings (although an error message will be displayed to that effect). --The default setting is --Apply Console Appender to Root Logger --Apply Pattern Layout to Console Appender --pattern is "% d {HH: mm: ss.SSS} [% t]% -5level% logger {36} --% msg% n " --Output log level is ERROR

ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console. Set system property 'log4j2.debug' to show Log4j2 internal initialization logging.
15:51:56.904 [main] FATAL Test - fatal!
15:51:56.907 [main] ERROR Test - error!

1. Minimum configuration file


<?xml version="1.0" encoding="UTF-8"?>

If you describe so far, the log will be output in the default format while no error will occur.

16:52:31.453 [main] FATAL Test - fatal!
16:52:31.453 [main] ERROR Test - error!

--You can specify the log output level of log4j2 itself by using the status attribute in the Configuration tag. --If there is a file called log4j2-test.xml, this one will be read with priority. This is convenient when you want to temporarily replace the settings. --In addition to xml format, you can also write in json format or yaml format. Also, the legacy properties format. --The priority is properties> yaml> json> xml. The rationale is unknown (why xml is the weakest!).

reference: http://logging.apache.org/log4j/2.x/manual/configuration.html#ConfigurationSyntax http://logging.apache.org/log4j/2.x/manual/configuration.html#AutomaticConfiguration

2. Minimal Appender and Logger

A combination of Console Appender with no options and RootLogger with just that. The name given by the name attribute of ʻAppender is associated by specifying it by the ref attribute of ʻAppenderRef of Logger.


<?xml version="1.0" encoding="UTF-8"?>
        <Console name="STDOUT">
            <AppenderRef ref="STDOUT"/>

A simple log of only messages is output.

--Appender defines the log output destination (output method), output layout, etc. --Logger specifies the log output target and the Appender to be used. Multiple Appenders can be specified. Even if you do not specify Appender, no error will occur, but of course the log will not be output anywhere.

--Console Appender defaults to standard output. If you want to output to standard error output, specify target = "SYSTEM_ERR". --Actually, even if the output destination is standard output, there are many cases where target = "SYSTEM_OUT" is explicitly described.

--By specifying level for Logger, you can control the log output level of that Logger.

<Root level="info">

reference: http://logging.apache.org/log4j/2.x/manual/configuration.html#Loggers http://logging.apache.org/log4j/2.x/manual/configuration.html#Appenders

3. Layout specification

To specify the output layout, specify Layout for Appender.

<Console name="STDOUT">
    <PatternLayout pattern="%d %p %m%n"/>
2017-10-24 18:12:23,469 FATAL fatal!
2017-10-24 18:12:23,472 ERROR error!
2017-10-24 18:12:23,472 WARN warn!
2017-10-24 18:12:23,472 INFO info!

Reference: http://logging.apache.org/log4j/2.x/manual/layouts.html

4. Child Logger

Define a child Logger of RootLogger as needed.

    <Logger name="Test">
        <AppenderRef ref="STDOUT"/>
        <AppenderRef ref="STDOUT"/>

--The name attribute is required for the child Logger, and specify the class or package to be logged. --Note that specifying a class name or package name that does not exist does not cause an error. --The name attribute cannot be specified for RootLogger.

2017-10-25 13:06:51,840 FATAL fatal!
2017-10-25 13:06:51,840 FATAL fatal!
2017-10-25 13:06:51,840 ERROR error!
2017-10-25 13:06:51,840 ERROR error!

Since Logger propagates from child to parent, logs are output twice if the log output conditions are the same. To suppress propagation, specify additivity = "false" in the child Logger.

<Logger name="Test" additivity="false">
2017-10-25 13:15:59,282 FATAL fatal!
2017-10-25 13:15:59,282 ERROR error!

Since RootLogger has no parent, additivity cannot be specified.

Reference: http://logging.apache.org/log4j/2.x/manual/configuration.html#Additivity

5. Filter

The filter is used when you want to control whether or not to output the log only under specific conditions. Filters can be set in the following four locations.

--Configuration --Filter for the entire context --Logger --Filter for a specific Logger --Appender --Filter for a specific Appender --AppenderRef --Filter for a specific Logger x Appender

When the log is output, it is judged that the filter is applied, and one of the following three statuses is returned.

--ACCEPT --Log output confirmed --DENY --Log non-output confirmed --NEUTRAL --Transfer judgment to the next filter

    <RegexFilter regex=".*err.*"/>

If you want to specify multiple filters, enclose them in Filters.

        <RegexFilter regex=".*err.*"/>
        <TimeFilter start="9:00:00" end="17:00:00"/>

--If multiple filters are set, the judgment will be performed in the defined order. --If ACCEPT or DENY is returned, the judgment is confirmed at that point, and the judgment of the remaining filters is not performed. --If NEUTRAL is returned, the judgment moves to the next filter. --If the next filter is no longer available, it will be treated as ACCEPT.

Reference: http://logging.apache.org/log4j/2.x/manual/filters.html

6. Properties

Property values can be defined and referenced in the configuration file.

        <Property name="myPattern">%d %p %m%n</Property>
        <Console name="STDOUT">
            <PatternLayout pattern="${myPattern}"/>

It can be used to extract common elements and literal values.

Reference: http://logging.apache.org/log4j/2.x/manual/configuration.html#Properties

7. Value reference

Various values such as system environment variables and system properties can be referenced in the configuration file.

--System environment variables -- $ {env: os}, $ {env: computername}, etc. --System properties -- $ {sys: java.home}, $ {sys: file.encoding}, etc.

Reference: http://logging.apache.org/log4j/2.x/manual/lookups.html

8. Script

There are mechanisms such as ScriptFilter and ScriptPatternSelector that work using scripts. The script can be written directly in the configuration file, or the script file can be referenced. In the former case, use the <Script> tag, and in the latter case, use the <ScriptFile> tag to define. You can specify the type of script with the language attribute, but the types that can be specified in the version / environment I tried this time were nashorn, Nashorn, js, JS, JavaScript, javascript, ECMAScript, ecmascript.

        <Script name="checkSunday" language="javascript"><![CDATA[
            var result;
            var sunday = 0;
            var today = new Date();
            var dayOfWeek = today.getDay();
            if (dayOfWeek == sunday) {
                result = true;
            } else {
                result = false;
        <ScriptRef ref="checkSunday"/>

reference: http://logging.apache.org/log4j/2.x/manual/configuration.html#Scripts http://logging.apache.org/log4j/2.x/manual/filters.html#Script

9. Splitting the configuration file

XInclude allows you to split a configuration file into multiple files.


<?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns:xi="http://www.w3.org/2001/XInclude">
            <AppenderRef ref="STDOUT"/>
    <xi:include href="log4j2-appender.xml"/>


<?xml version="1.0" encoding="UTF-8"?>
    <Console name="STDOUT">
        <PatternLayout pattern="%d %p %m%n"/>

Reference: http://logging.apache.org/log4j/2.x/manual/configuration.html#XInclude

Recommended Posts

Understand the basic mechanism of log4j2.xml
Understand the basics of docker
The basic basis of Swift dialogs
The basic basis of Swift's Delegate
Understand the basics of Android Audio Record
Understand the official sample Coffee of Dagger2
About the mechanism of the Web and HTTP
The basic basis of Swift custom cells
Learn the rudimentary mechanism and usage of Gradle 4.4
[For beginners] Quickly understand the basics of Java 8 Lambda
Understand the characteristics of Scala in 5 minutes (Introduction to Scala)
Judgment of the calendar
The world of clara-rules (4)
Image processing: The basic structure of the image read by the program
The world of clara-rules (1)
Let's understand the function!
The world of clara-rules (3)
Basic format of Dockefile
The world of clara-rules (5)
The idea of quicksort
The idea of jQuery
I didn't understand the behavior of Java Scanner and .nextLine ().
Review the basic knowledge of ruby that is often forgotten
Now, I understand the coordinate transformation method of UIView (Swift)
I tried to summarize the basic grammar of Ruby briefly
Follow function association memorandum (understand the description of the User model)
Aiming for a basic understanding of the flow of recursive processing
Basic methods of Ruby hashes
About the handling of Null
Background and mechanism of Fabric-loader
Docker monitoring-explaining the basics of basics-
Basic knowledge of SQL statements
Basic methods of Ruby arrays
[Docker] Introduction of basic Docker Instruction
About the description of Docker-compose.yml
The play of instantiating java.lang.Void
Let's understand the if statement!
Explanation of the FizzBuzz problem
Let's understand the guard statement!
Understand the helper method form_with
The basics of Swift's TableView
Super basic usage of Eclipse
Median of the three values
[Ruby] List of basic commands
Let's understand the for-in statement!
The illusion of object orientation
Let's understand the switch statement!
Summary of basic functions of ImageJ
Switch the version of bundler
Review of Ruby basic grammar
I think I understand the reuse of cells, but I don't understand at all.
I investigated the mechanism of attr_accessor (* Hoge :: ATTRIBUTES) that I sometimes see
I want to understand the flow of Spring processing request parameters
The point of addiction when performing basic authentication with Java URLConnection
I examined the concept of the process to understand how Docker works