Level and use of log4j logs

Source: Internet
Author: User
Tags log4j

1, the level of the log:

We're going to call the logger method now, but there are a lot of methods in this logger object, so we need to understand the log level of log4j, log4j set the default levels: Trace<debug<info<warn<error <fatal and so on. Here is to explain:

1 levels are included in the relationship, meaning that if you set the log level to be trace, the log will be output greater than or equal to this level.

2 Basically the default level is not much different, is a default setting. You can define the level by its API. You can also call these methods at will, but you have to do well in the configuration file, otherwise you will not be able to log the role, but also difficult to read, the equivalent of a specification, you have to fully define a set of can also, do not have much need.

3 The meaning of this different level is easy to understand, here is a brief introduction:

Trace: Is tracking, that is, the program pushes the following, you can write a trace output, so trace should be very much, but it doesn't matter, we can set the minimum log level to not let him output.

Debug: Debug, I usually just use this as the lowest level, and trace doesn't use it at all. Is it okay to use the debug feature of Eclipse or idea?

Info: Output The information you are interested in or important, which is the most used.

Warn: Some of the information is not an error message, but there are also some hints for the programmer, similar to the validation of the code in eclipse that there is no error or warn (not a mistake but also note, for example, the following depressed method).

Error: Wrong message. Use more.

Fatal: The level is higher. Major error, this level you can directly stop the program, it should not be a mistake. Not so nervous, in fact, is a matter of degree.

2, log call:

Here casually write a class, the call is so simple, log4j the core of 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, listed separately, is the one that you want to call at the beginning of a method or program logic, and the basic meaning of Logger.trace ("entry")
        Logger.error ("Did it again!");   Error level information, the parameter is the information you output
        logger.info ("I am info information");    Info level information
        logger.debug ("I am Debug Information");
        Logger.warn ("I am warn Information");
        Logger.fatal ("I am fatal Information");
        Logger.log (Level.debug, "I am DEBUG information");   This is to make the level type call: Who is idle to call this, not necessarily oh.
        logger.exit ();    The end method corresponding to entry (), and Logger.trace ("exit"); one meaning return
        false;
    }
If there is no custom profile, the above class is 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 am FATAL information
See, only >=error log output is coming (this is because log4j has a default configuration, its log level is error, output only console). If I have already defined the log, I change the log level to trace, and the output becomes the following:

19:11:36.941 TRACE Cn.lsw.base.log4j2.Hello hello-entry
19:11:36.951 ERROR Cn.lsw.base.log4j2.Hello Hello-di D It again!
19:11:36.951 Info  Cn.lsw.base.log4j2.Hello Hello-I'm info information
19:11:36.951 DEBUG Cn.lsw.base.log4j2.Hello 15 Hello-I'm the debug information
19:11:36.951 WARN  Cn.lsw.base.log4j2.Hello Hello-I'm WARN information
19:11:36.952 FATAL Cn.lsw.base.log4j2.Hello Hello-I'm fatal information
19:11:36.952 debug Cn.lsw.base.log4j2.Hello Hello-I'm debug information
19:11:36.952 TRACE Cn.lsw.base.log4j2.Hello Hello-exit

All the logs are printed out, you can compare the above code to see.

3. Configuration file:

It's time to get down to business.

I thought log4j 2 should have a default configuration file, but it doesn't seem to be found, the following configuration file is equivalent to the default configuration:

<?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>

As long as we change the level attribute of Configuration>loggers>root to trace, we can output all the information we just wrote. Believe that the use of log4j is not unfamiliar to this profile, log4j traditional configuration has been. properties file, the form of key-value pairs, which configuration is very bad, but basically we can see from this configuration file log4j 1 shadow, nothing but Appender, Layout and the like, meaning is basically the same.

Here is not prepared to carefully talk about the configuration file, there is no need, you just know some basic configuration on it. I write a few configuration files here, and give some comments and explanations, basically can be used.

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 let this logger output trace information, the other is the error level-->
        <!--
        additivity Open, because this logger is also satisfied with root, so will be printed two times.
        but the level of root logger is error, why the trace information in bar is also 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>

Let me briefly introduce the following configuration file.

1 The root node is configuration, and then there are two subnodes: Appenders and loggers (all plural, meaning that you can define a lot of appender and logger) (if you want to look at the structure of this XML in detail, You can go under the jar pack to find XSD files and DTD files.

2 Appenders: This is defined below is the various appender, is the output, there are many categories, here is not much to say (easy to cause understanding and interpretation of the pressure, at the beginning may not be able to understand, equal to white speaking), first look at this example, only a console, These nodes are not arbitrarily named, console is the output console meaning. Then set some properties for this output, here set the patternlayout is the output format, is basically the previous time, thread, level, logger name, log information and so on, almost, you can check their grammar rules.

3 loggers A number of logger are defined below, and these logger are differentiated by name to configure different outputs for different logger by referencing the logger defined above, noting that The value referenced by Appender-ref is the name of each appender above, not the node names.

This example is to illustrate what. Let's talk about the name of the logger (mentioned above).

4, the name of the mechanism:

We see here that it's important to have the name in the config file, and yes, this name is not allowed to go anywhere. This mechanism means very simple. Just like Java package, like one of our packages: Cn.lsw.base.log4j2. Also, we can find that when we generate the Logger object in front, the name is passed through Hello.class.getName (); Such a method, why do this. Very simple, because there is a problem of so-called logger inheritance. For example, if you define a logger for cn.lsw.base, then he also applies to cn.lsw.base.lgo4j2 this logger. The inheritance of names is separated by dots (.). Then you can guess that there is a child node in the top loggers that is not logger but root, and this root does not have the name attribute. This root is equivalent to the root node. All of your logger are applicable to this logger, so even if you get a lot of logger through the class name. Class.getname () In many classes, and do not configure under the loggers of the configuration file, they can also output Because they all inherit the root log configuration.

Our above configuration file also defines a logger, his name is Cn.lsw.base.log4j2.Hello, the name is actually through the front of the Hello.class.getName (); We get, in order to give him a separate configuration, here is generated for this class of logger, the above configuration basically means that only cn.lsw.base.log4j2.Hello this logger output trace information, that is, his log level is trace, Other logger inherit the log configuration of root, log level is error, can only print out error and above level of log. If the Logger Name property is changed to Cn.lsw.base, then all logger under this package will inherit this log configuration (the package here is the meaning of the "package" of the log4j logger name, not the Java package, You have to give hello to create a name called "Myhello" logger, he can not inherit cn.lsw.base this configuration.

That someone will ask, he should not also inherit the configuration of the root, then will not output two times. We have explained in the configuration file that if you set the additivity= "false", you will not output two times, otherwise, look at the following output:

Here is to add a class to do the comparison:

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 program.");
        Hello hello= new Hello ();
for        (int i = 0; i < 10000;i++) {
            if (!hello.hello ()) {
                logger.error ("Hello");
            }        }
        Logger.trace ("Exit program.");
    }

Here first change the configuration file for easy control, One is just the first logger name or cn.lsw.base.log4j2.hello,additivity to remove or to true (because the default is true, so you can remove), and the second is to change the level of root to the info convenient observation.

Then run test to see the log output of the console:

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.log4j  2.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 am info info 2013-12-20 19:59:42.542 [main] info cn.lsw.base. Log4j2. Hello-I'm info info 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 am the debug information 2013-12-20 19:59:42.542 [main] WARN Cn.lsw.base.log4j2.Hello-I am WARN information 2013-1 2-20 19:59:42.542 [main] WARN Cn.lsw.base.log4j2.Hello-I am WARN information 2013-12-20 19:59:42.542 [main] FATAL cn.lsw.base.log4j2 .  Hello-I am FATAL information 2013-12-20 19:59:42.542 [main] FATAL Cn.lsw.base.log4j2.Hello-I am FATAL information 2013-12-20 19:59:42.542 [main] DEBUG Cn.lsw.base. log4j2.  Hello-I am the debug information 2013-12-20 19:59:42.542 [main] Debug Cn.lsw.base.log4j2.Hello-I am 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 you can see, the trace log for test has no output because he inherits the log configuration of root and outputs only the log at info level. Hello prints out trace and above-level logs, but each output is two times. You can try, the first logger level should be the error, then error above the grade is also output two times. At this point, just add additivity to false to avoid this problem.

Of course, you can do a different configuration for each logger under the configuration file, or you can use the inheritance mechanism to make different configurations for the logs under different packages. Because loggers can write a lot of song logger below.

Here's a slightly more complicated example:

<?xml version= "1.0" encoding= "UTF-8"?> <configuration status= "error" > <!--first define all appender--> < Appenders> <!--The configuration of this output console--> <console name= "console" target= "System_out" > <! --the console outputs only level and above levels of information (Onmatch), other direct rejections (Onmismatch)--> <thresholdfilter level= "Trace" onmatch= "ACCEPT" on Mismatch= "DENY"/> <!--This is known as the format of the output log--> <patternlayout pattern= "%d{hh:mm:ss. SSS}%-5level%class{36}%l%m-%msg%xex%n "/> </Console> <!--files will print out all the information, this log is automatically emptied every time the program is run, by app The End property determines that this is also useful for temporary testing with--> <file name= "log" filename= "Log/test.log" append= "false" > <patte Rnlayout pattern= "%d{hh:mm:ss. SSS}%-5level%class{36}%l%m-%msg%xex%n "/> </File> <!--This will print out all the information, the size of the log will be
                     Automatically deposit under the folder established by year-month and compress as archive--> <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 50MB size="/> </RollingFile> </appenders> <!--then define logger, only the Appender,appender defined logger and introduced will take effect--> <log Gers> <!--establish a default root logger--> <root level= "Trace" > <appender-ref ref= "Roll" Ingfile "/> <appender-ref ref=" Console "/> </root> </loggers> </configuratio N>

It is not complicated to say complex, this one example is mainly to talk about Appenders.

Here defines three appender,console,file,rollingfile, see meaning basically also understand, the second is write file, the third is "loop" log file, meaning is the log file is larger than the threshold time, began to write a new log file.

The comments in our configuration file are detailed here. So everyone saw it for themselves. One of the more interesting is thresholdfilter, a filter, in fact, each appender can define a lot of filter, this function is very useful. If you want to select the console can only output the category of error above, you use Thresholdfilter, the level set to Error,onmatch= "ACCEPT" onmismatch= "deny" means that the match is accepted, or directly refused, Of course, there are other options, such as handing over to other filters to deal with the kind of, details of their own to ponder it.









Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.