log4j Use Tutorials (how to use Log4j2) _java

Source: Internet
Author: User
Tags inheritance log4j

1. Go to the official Download log4j 2, import jar package, basically you only need to import the following two jar packages on it (xx is a messy version number):

Log4j-core-xx.jar

Log4j-api-xx.jar

2. Import into your project: This will not be said.

3. Start using:

We know that to use the log4j log in a class, you only need to declare the following member variable (in fact not necessarily a member variable, just for convenience)

Copy Code code as follows:

private static Logger Logger = Logmanager.getlogger (MyApp.class.getName ());

GetLogger has a parameter that specifies the name of the logger, which is needed in the configuration file, and this will be later.

By declaring the Logger object, we can use it in the code.

4. 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.

5. Log Call:

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

Copy Code code as follows:

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, which is listed separately in the hope that you will be called at the beginning of a method or program logic, and that Logger.trace ("entry") basically means
Logger.error ("Did it again!"); Error level information, the parameter is the information you output
Logger.info ("I am info info"); Info-level Information
Logger.debug ("I am the 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 the entry () and the Logger.trace ("exit"); a meaning
return false;
}
}

If there is no custom profile, the above class is writing a main method, the console will enter the following:

Copy Code code as follows:

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:

Copy Code code as follows:

19:11:36.941 TRACE Cn.lsw.base.log4j2.Hello Hello-entry
19:11:36.951 ERROR Cn.lsw.base.log4j2.Hello Hello-did it again!
19:11:36.951 Info Cn.lsw.base.log4j2.Hello Hello-I'm info info
19:11:36.951 Debug Cn.lsw.base.log4j2.Hello Hello-I'm 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.

6. 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:

Copy Code code as follows:

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

Copy Code code as follows:

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

What does this example mean? Let's talk about the name of the logger (mentioned above).

7. The mechanism of name:

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 is not also should 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:

Copy Code code as follows:

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:

Copy Code code as follows:

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 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'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 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:

Copy Code code as follows:

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

<configuration status= "Error" >
<!--first define all the appender-->
<appenders>
<!--configuration of this output console-->
<console name= "Console" target= "System_out" >
<!--the console outputs only level and above levels of information (Onmatch), and other direct rejections (Onmismatch)-->
<thresholdfilter level= "Trace" onmatch= "ACCEPT" onmismatch= "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>
<!--file will print out all the information, this log every time the program will automatically empty, 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 out all the information, each time size exceeds size, this size log will automatically be deposited under the year-month folder and compressed, as an 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 size= "50MB"/>
</RollingFile>
</appenders>
<!--then define logger, and only the appender,appender that define logger and introduce them will take effect-->
<loggers>
<!--to establish a default root logger-->
<root level= "Trace" >
<appender-ref ref= "Rollingfile"/>
<appender-ref ref= "Console"/>
</root>

</loggers>
</configuration>

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.

Why add a configuration file like this? In fact, this configuration file I feel very good, his practicality is in the following:

8. A practical configuration file:

We use the log on the one hand is to record the program running information, in the wrong time to troubleshoot and so on, and sometimes when debugging also like to use the log. Therefore, the log if the record is very messy, it seems inconvenient. So I might have some of the following requirements:

1) I'm debugging a class, so, I do not want to let other classes or the log output of the package, otherwise there will be a lot of content, so you can modify the above root level is the highest (or with the error of caution), and then add a logger configuration for the class, such as the first configuration file in the settings, Set his level to trace or debug, and then we give a appender-ref is the definition of the file that Appender (a total of three appender, remember), The advantage of this appender is that there is a append false property, so that each run will empty the last log, so that will not be because of the debugging and increase the content of the file, it is convenient to check up, this and output to the console on an effect.

2 I have basically deployed the program, and then I have to run for a long time. I need to record the following several logs, first, the console output all the information above the error level. Second, I want to have a file output is all the Debug or info above information, similar to do the program record or something. Third, I want to separate for the error information output to a separate file, if the wrong, only check this profile is good, not to deal with too many logs, looks like a big head. How to do it, very simple.

> First, add a console-type Appender under Appenders and set the level to error by adding a thresholdfilter. (modified directly in the console of the configuration file Appender)

> Secondly, add a file type of Appender (also can be rollingfile or other file output type), and then set the Thresholdfilter level as error, to file Your error log should not be so many, do not need to have multiple error level log files exist, or your program can be basically rewritten.

Here you can add a appender that reads as follows:

Copy Code code as follows:

<file name= "ERROR" filename= "Logs/error.log" >
<thresholdfilter level= "error" onmatch= "ACCEPT" onmismatch= "DENY"/>
<patternlayout pattern= "%d{yyyy. Mm.dd ' at ' HH:mm:ss z}%-5level%class{36}%l%m-%msg%xex%n '/>
</File>

and reference in a logger (such as root) in loggers (the root node joins this row as a child node).

Copy Code code as follows:

<appender-ref ref= "ERROR"/>

> Then, add a rollingfile appender, set basically the same configuration file as above.

> Finally, make the appropriate configuration in the logger. However, if your logger also have log level configuration, if the level is above the error, your appender inside also will not output error information.

Remember the test class above has a commented out for loop? This is to do in the configuration file rollingfile that Appender configuration, uncomment, run the business once or several times, look at your output configuration file where he is "rollingfile", here give me a screenshot of the test: (Here you can put < Sizebasedtriggeringpolicy size= "50MB"/> Here to the size of 2MB, to generate 50MB log is relatively slow. For the convenience of observation! The console's thresholdfilter level is then set to higher levels such as error, otherwise the console outputs too many things.

The first part (the figure is labeled 1), is the jar package I joined;

The second part is file this appender generated log files, you will find that you run many times, the log in this file is covered.

The third part is rollingfile this appender generated configuration file, you can find that, The default is the App.log this log, each time more than 2MB, will generate the corresponding year-month folder, and the development of a named format log file, but is compressed into the GZ format file, open Explorer found this file only 11KB, after decompression is 2MB.

Finally, I hope this tutorial can help everyone!

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.