Log4j 2 tutorial

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

  The benefits of Log4j 2 is not everybody said, if you search, 2, that you have knowledge of him, and want to use it, so here directly to the.

  1 to download the official log4j 2, Import the jar package, basically you just need to import the following two jar package can be (XX is at sixes and sevens version number):

    log4j-core-xx.jar

    log4j-api-xx.jar

  2 Introduction to your project: This is not to say.

  3 began to use:

    We know, want to use the log4j log records in a class, only need to affirm the following member variables (actually not certain if the member variables, only for the convenience of call.)

private static Logger logger = LogManager.getLogger(MyApp.class.getName());

    Here getLogger is to specify a parameter is the name of this logger, this name in the configuration file is needed, the later again.

    Declaration of the Logger object, we can use him in the code.

  4 log level:

    We have to call the logger method of the now, but in this Logger object, there are a lot of ways, it must first understand the log4j log level, log4j provides several levels of default: trace<debug<info<warn<error<fatal. Here to explain:

    1)Between levels is included, if you set the logging level is trace, is greater than or equal to the level of the log will be output.

    2)The default level basically not much difference, is a default setting. You can through its own definition API level. You also can call these methods, but you need to be in inside the configuration file handle, or will not to log function, but also not easy to read, the equivalent of a specification, you should define a set of can, need not not necessary.

    3)The different levels of meaning are all very easy to understand, here is simple to introduce:

    trace: Track, is to promote the program, you can write a trace output, so trace should be much more special, but never mind, we can set the minimum log level not to let him out.

    debug: Debugging Mody, I usually only use this as the lowest level, trace not. In no way can use eclipse or idea debug function is good.

    info: Output your interest or important information, this up.

    warn: Some information is not false information, but also give some hints of programmers, validation is similar to the eclipse code is not error and warn (for example, the following depressed method is not wrong but also note,).

    error: Error message. With more and more.

    fatal: A relatively high level. Big mistake, this level you can stop the program, should not be wrong! Need not be so nervous, in fact, is a matter of degree.

  5 log calls:

    Here, just write a class, the call is so simple, the core of the log4j in the configuration file.

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Hello {

    static Logger logger = LogManager.getLogger(Hello.class.getName());

    public boolean hello() {
        logger.entry();   //Trace level information, separately is to call you when you started in a method or program logic, and logger.trace ("entry") basic a meaning
        logger.error("Did it again!");   //The error levels of information, information output parameter is you
        logger.info("I'm info information");    //Info level information
        logger.debug("I'm debug information");
        logger.warn("I'm warn information");
        logger.fatal("I'm fatal information");
        logger.log(Level.DEBUG, "I'm debug information");   //This is the development of Level type of call: who is idle and call this, not necessarily oh!
        logger.exit();    //And the entry () method to end the correspondence, and the logger.trace ("exit"); a meaning
        return false;
    }
}  

  If no custom configuration files, this kind of writing a main method, the console will enter the following:

  

19:09:40.256 [main] ERROR cn.lsw.base.log4j2.Hello - Did it again!
19:09:40.260 [main] FATAL cn.lsw.base.log4j2.Hello I'm fatal information

  See no, only > =ERROR log output. (this is because the Log4j has a default configuration, its log level is ERROR, the output only console). If I have a good definition of the log, I put the log level to TRACE, the output will be the following:  

19:11:36.941 TRACE cn.lsw.base.log4j2.Hello 12 hello - entry
19:11:36.951 ERROR cn.lsw.base.log4j2.Hello 13 hello - Did it again!
19:11:36.951 INFO  cn.lsw.base.log4j2.Hello 14 Hello I'm info information
19:11:36.951 DEBUG cn.lsw.base.log4j2.Hello 15 Hello I'm debug information
19:11:36.951 WARN  cn.lsw.base.log4j2.Hello 16 Hello I'm warn information
19:11:36.952 FATAL cn.lsw.base.log4j2.Hello 17 Hello I'm fatal information
19:11:36.952 DEBUG cn.lsw.base.log4j2.Hello 18 Hello I'm debug information
19:11:36.952 TRACE cn.lsw.base.log4j2.Hello 19 hello - exit

  All the logs are printed out, we can control the above code to see.

  The 6 configuration file:

  Now the business.

  Originally thought that the Log4J 2 should have a default configuration file, but it seems not found, the configuration file is equivalent to the default configuration(from ):

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

  And we as long as the configuration> loggers> level root property to trace, you can just write all information output. Believe in a Log4j are not unfamiliar to the configuration file, Log4J traditional configuration has been the key to the.Properties file, the form, the configuration is not good-looking, but basically we see Log4J 1 shadow from the configuration file can also, is none other than appender, such as layout, meaning is the basic the same.

  Here is not prepared to carefully about the configuration file, not what is necessary, as long as we know some basic configuration can be. I'm here to write several configuration files, and gave some comments and explanations, basically can be used.

 The first example:

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="OFF">
    <appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
    </appenders>
    <loggers>
        <!--We only make the logger output trace information, the other is error level-->
        <!--
        Additivity opens it, because the logger is also meet root, so will be printed two times. 
        But root logger level is error, why the Bar inside the trace information is printed two times
        -->
        <logger name="cn.lsw.base.log4j2.Hello" level="trace" additivity="false">
            <appender-ref ref="Console"/>
        </logger>
        <root level="error">
            <appender-ref ref="Console"/>
        </root>
    </loggers>
</configuration>

 Briefly introduce the configuration file.

  1)The root node configuration, then there are two sub nodes: Appenders and loggers (both are complex, meaning that can be defined in many appender and logger) (if you want to see the structure, the XML in detail what can go to the jar package to find XSD and DTD files)

  2)appenders: The following definition is the appender, is the output, there are a lot of categories, also don't say here (easy to cause the understanding and interpretation of pressure, the beginning may not be able to understand, to speak), look at this example, only one Console, these nodes can not casually named, Console is the output console. Then according to the output set some properties, set here PatternLayout is the output format, basically is the front time, thread, level, logger name, log information, almost, can check out their grammar rules.

  3)Loggers below will define many logger, these logger were distinguished by name, to different output for different logger configurations, is quoted by the above definition of logger.

  In order to explain what this example? We want to talk about the logger name (name) (mentioned).

  Mechanism of 7 name: (can refer to: http://logging.apache.org/log4j/2.x/manual/architecture.html)

   Here we see the configuration file is name important, yes, the name can't just play (in fact can easily play). This mechanism is very simple. Is similar to java package, for example, one of our bags: cn.lsw.base.log4j2. But, when we can be found in front of the generation of the Logger object, named is through the Hello.class.getName (); this way, why? Is very simple, because the so-called Logger inheritance problems. For example, if you cn.lsw.base to define a logger, then he is also applicable to the cn.lsw.base.lgo4j2 logger. The name of the inheritance is through the point (delimited.). Then you can guess it loggers there is a child node is not logger but root, but the root has no name property. This root is equivalent to the root node. All of your logger application and the logger,.Class.getName, even if the class name you through in many class () to get a lot of logger, and no configuration in the following configuration file loggers, they are able to output, because they have inherited the root log configuration.

  Our above the configuration file defines a logger, His name is cn.lsw.base.log4j2.Hello , This name is passed in front of the Hello.class.getName (obtained), We gave him a single configuration in order to, Here is generated for this class of logger, The above configuration basic meaning is only cn.lsw.base.log4j2.Hello the logger output trace information, It was his log level is trace, Other logger inherited root log configuration, The log level is error, Only print ERROR and above the level of the log. If the name attribute of logger into cn.lsw.base, All the package logger below will inherit the log configuration (where the package is the log4j logger name "package" meaning, Not java package, You are not to give Hello a name for the "myhello" logger, He could not inherit the cn.lsw.base configuration.


  Then someone will ask, he should not be a successor to the root configuration, it will output two times? We give the explanation in the configuration file, if you set the additivity= "false", will not output two times, otherwise, output, see below:

  Here to do comparison in joining a class:  

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Test {


    private static Logger logger = LogManager.getLogger(Test.class.getName());

    public static void main(String[] args) {

        logger.trace("Start the program");
        Hello hello= new Hello();
//        for (int i = 0; i <10000;i++){
            if (!hello.hello()) {
                logger.error("hello");
            }
//        }
        logger.trace("Exit the program");
    }
}  

  Here the first configuration file change convenient control, one is just the name of the first logger or cn.lsw.base.log4j2.Hello, additivity is removed or changed to true (because the default is true, so it can be removed), second is the root level info for convenient observation.  

  Then run the Test, see the console log output:

2013-12-20 19:59:42.538 [main] INFO  cn.lsw.base.log4j2.Test - test
2013-12-20 19:59:42.541 [main] TRACE cn.lsw.base.log4j2.Hello - entry
2013-12-20 19:59:42.541 [main] TRACE cn.lsw.base.log4j2.Hello - entry
2013-12-20 19:59:42.542 [main] ERROR cn.lsw.base.log4j2.Hello - Did it again!
2013-12-20 19:59:42.542 [main] ERROR cn.lsw.base.log4j2.Hello - Did it again!
2013-12-20 19:59:42.542 [main] INFO cn.lsw.base.log4j2.Hello I'm info information
2013-12-20 19:59:42.542 [main] INFO cn.lsw.base.log4j2.Hello I'm info information
2013-12-20 19:59:42.542 [main] DEBUG cn.lsw.base.log4j2.Hello I'm debug information
2013-12-20 19:59:42.542 [main] DEBUG cn.lsw.base.log4j2.Hello I'm debug information
2013-12-20 19:59:42.542 [main] WARN cn.lsw.base.log4j2.Hello I'm warn information
2013-12-20 19:59:42.542 [main] WARN cn.lsw.base.log4j2.Hello I'm warn information
2013-12-20 19:59:42.542 [main] FATAL cn.lsw.base.log4j2.Hello I'm fatal information
2013-12-20 19:59:42.542 [main] FATAL cn.lsw.base.log4j2.Hello I'm fatal information
2013-12-20 19:59:42.542 [main] DEBUG cn.lsw.base.log4j2.Hello I'm debug information
2013-12-20 19:59:42.542 [main] DEBUG cn.lsw.base.log4j2.Hello I'm debug information
2013-12-20 19:59:42.543 [main] TRACE cn.lsw.base.log4j2.Hello - exit
2013-12-20 19:59:42.543 [main] TRACE cn.lsw.base.log4j2.Hello - exit
2013-12-20 19:59:42.543 [main] ERROR cn.lsw.base.log4j2.Test - hello

  As can be seen, the Test trace log no output, because he has inherited the root log configuration, only the output of info is above the level of the log. The Hello output of trace and above the level of the log, but each output two times. You can try, the first logger level for the error, then the error level and above is output two times. At this time, as long as the additivity plus false can avoid this problem.

  Of course, you can for each logger are different in configuration files below, also can through the inheritance mechanism of different packages, the following log do different configuration. Because the loggers below can write a lot of songs logger.

  Under a slightly more complex example:

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

<configuration status="error">
    <!--The first definition of all appender-->
    <appenders>
        <!--The output console configuration-->
        <Console name="Console" target="SYSTEM_OUT">
            <!--The console output only level and above the level of the information (onMatch), directly to the other(onMismatch)-->
            <ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY"/>
            <!--This all know is the output log format-->
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
        </Console>
        <!--Document will print out all the information, the log every time you run the program will automatically clear, determined by the append property, this is also very useful, suitable for temporary test-->
        <File name="log" fileName="log/test.log" append="false">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
        </File>

        <!--This will print all the information, each size is more than size, then the size size of the log will automatically in the following year month was built according to the folder and file compression, as-->
        <RollingFile name="RollingFile" fileName="logs/app.log"
                     filePattern="log/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
            <PatternLayout pattern="%d{yyyy-MM-dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>
            <SizeBasedTriggeringPolicy size="50MB"/>
        </RollingFile>
    </appenders>
    <!--Then the definition of logger, only the definition of logger and the introduction of the appender, the appender will take effect-->
    <loggers>
        <!--Create a default root logger-->
        <root level="trace">
            <appender-ref ref="RollingFile"/>
            <appender-ref ref="Console"/>
        </root>

    </loggers>
</configuration>

  Complex, in fact is not complicated, this example is mainly to talk about Appenders.

  Here the definition of three appender, Console, File, RollingFile, look I know, second is written to the file, the third is "cycle" of the log file, you log file is larger than the threshold, he began to write a new log file.

  Here we profile which notes are detailed. So you see for yourself. There is a very interesting is the ThresholdFilter, a filter, in fact, each appender can define a filter, this function is very useful. If you want to select the console above can output ERROR categories, You can use ThresholdFilter, The level set ERROR, onMatch="ACCEPT" onMismatch="DENY" Mean matching accept, Or directly refuse, Of course, there are other options, For example to other filters to deal with such, The details you go figure.

  Why should add such a configuration file? In fact, the configuration files, I feel pretty good, his utility below:

  8 a practical configuration file:

  We use the log is to record a program information, investigation in the wrong time and so on, sometimes also like to use debug log. So, if the log record is a mess of words, do not look easy. So I may have some of the following requirements:

  1)I'm debugging a class, So, I don't want to let the other class or package log output, Otherwise they will be a lot of content, So, You can modify the above root level was the highest (or the prudent use ERROR), Then, One for the logger configuration, Such as the first setting in the configuration file, His level set trace or debug like, Then we give a definition of appender-ref is File the appender (a total of three appender, Do you remember), The benefit of this appender is a append false attribute, Such, Each operation will clear the last log, It wouldn't have been debugging and increased the contents of this file, It is also easy to check, This and the output to the console as a result.

  2)I have been basically deployment of a good program, and I want to run for a long time. I need to record the following log, first, the console output all of the above error level information. Second, I want to have a file output is all debug or info more information, similar to what the program recording. Third, I want to alone for more than ERROR information output to a separate file, if wrong, only check the configuration file is good, not to deal with too many log, seems to have a big head. How to do it, is very simple.

  First, add a Console type in the Appenders below the appender, by adding a ThresholdFilter level set to error.

  Secondly, Add a File type of appender (also RollingFile or other file types), Then by setting the ThresholdFilter level error, Set to File to, Your error log should not so much, Do not need to have multiple error level log file exists, Otherwise your application basically can override the.

  Then, add a RollingFile appender, the configuration file settings basically same as above.

  Finally, for the corresponding configuration in logger. But if your logger is log level configuration, if the level is above error, your appender will not output error information.

  Remember the Test class above there is a comment out the for cycle? This is to do the configuration file RollingFile in the appender configuration, Uncomment, Operators once or several times, Look at the output profile your place, He is how to "RollingFile", Here's an I test (screenshots: Here you can use <SizeBasedTriggeringPolicy size= "50MB" /> where size into 2MB, To generate the 50MB log or slow. In order to facilitate the observation! Then Console ThresholdFilter level set to error this higher level, or too many console output.)

  

  The first part (shown in the logo for the 1), I joined the jar package,

  The second part is the File appender generated log files, you'll find out you run many times, this file in the log is covered.

  The third part is the RollingFile appender generates the configuration file, Can be found, The default is the establishment of the app.log log, Every time more than 2MB, It will generate the corresponding year month folder, And the development of naming format log file, And it is compressed into GZ format file, Open windows explorer found this file is only 11KB, After decompression is 2MB.

  Finally, hope that this tutorial will help you!

  



  

    

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Ingemar at April 17, 2014 - 9:32 AM