Log4j 2 tutorial

Source: Internet
Author: User

The benefits of Log4j 2 will not be discussed with everyone. If you search for 2, it means you have some knowledge about it and want to use it, so you can get started directly here.

 1. Download log4j 2 from the official website.To import the jar package, you only need to import the following two jar packages (xx is a messy version ):

Log4j-core-xx.jar

Log4j-api-xx.jar

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

 3. Start Using:

We know that to use log4j to record logs in a class, we only need to declare the following member variables (in fact, it is not necessarily a member variable, just for convenience of calling)

  Logger logger = LogManager.getLogger(MyApp..getName());

Here, the getLogger parameter specifies the name of this logger, which is required in the configuration file.

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

 4. Log Level:

We need to call the logger method now, but there are many methods in this Logger object, so we need to first understand the Log Level of log4j. log4j defines the default levels: trace <debug <info <warn <error <fatal, etc. Here we want to explain:

1) there is a inclusion relationship between levels, which means that if you set the log level to trace, logs greater than or equal to this level will be output.

2) The default level is basically the same, that is, a default setting. You can define the level through its API. You can also call these methods at will, but you have to handle them well in the configuration file. Otherwise, the log will not function and it will not be easy to read, which is equivalent to a specification, you can define a set completely without much need.

3) The meanings of different levels are easy to understand. Here is a brief introduction:

Trace: Tracing means that the program advances below. You can write a trace output, so there should be a lot of traces, but it doesn't matter. We can set the lowest log level to prevent the output.

Debug: debugging, I usually only use this as the lowest level, and trace is not used at all. Is there no way to use the debug function of eclipse or idea.

Info: output the information that you are interested in or that is the most useful.

Warn: Some information is not an error message, but some prompts should also be given to the programmer. Similar to the code verification in eclipse, there are not error and warn (not an error, but please note that, for example, the following depressed method ).

Error: error message. It is also widely used.

Fatal: The level is relatively high. Major errors. You can stop the program directly at this level. Shouldn't it be an error! Don't be so nervous, it's actually a level of problem.

 5. Log call:

Write a class at Will here, and the call is so simple. The core of log4j is the configuration file.

Logger logger = LogManager. getLogger (Hello. logger. error ("Did it again! "); Logger.info (" I am info "); logger. debug ("I am debug information" "I am warn information" "I am fatal information" "I am debug information"); logger. exit ();

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

  

19:09:40. 256 19:09:40. 260 FATAL cn. lsw. base. log4j2. Hello-I am fatal Information

No, only logs with> = ERROR are output (this is because Log4j has a default configuration. Its log level is ERROR, and the output is only on the console ). If I have defined the log, I have changed the log level to TRACE, and the output will be as follows:

19:11:36.941 TRACE cn.lsw.base.log4j2.Hello 1219:11:36.951 ERROR cn.lsw.base.log4j2.Hello 1319:11:36.951 INFO  cn.lsw.base.log4j2.Hello 1419:11:36.951 DEBUG cn.lsw.base.log4j2.Hello 1519:11:36.951 WARN  cn.lsw.base.log4j2.Hello 1619:11:36.952 FATAL cn.lsw.base.log4j2.Hello 1719:11:36.952 DEBUG cn.lsw.base.log4j2.Hello 1819:11:36.952 TRACE cn.lsw.base.log4j2.Hello 19 hello - exit

All the logs are printed. You can check the above Code.

  6. configuration file:

Now the question is starting.

I thought that Log4J 2 should have a default configuration file, but it seems that it is not found, the following configuration file is equivalent to the default configuration (from http://blog.csdn.net/welcome000yy/article/details/7962668 ):

                                                              

You only need to change the level Attribute of configuration> loggers> root to trace to output all the information you just wrote. I believe that people who have used Log4j are not unfamiliar with this configuration file. The traditional Log4J configuration has always been. properties file, in the form of a key-value pair, the configuration method is not good-looking, but basically we can see the shadow of Log4J 1 from this configuration file, which is nothing more than appender, layout, etc, the meaning is also basically the same.

There is no need to explain the configuration file carefully. You only need to know some basic configurations. I have written several configuration files and provided some comments and explanations, which are basically usable.

Example 1:

                                                                                                                    

First, we will briefly introduce the configuration file below the idea.

1) configure the root node, and then there are two subnodes: appenders and loggers (both are plural, meaning that many appender and logger can be defined) (If you want to take a detailed look at the xml structure, you can go to the jar package to find the xsd file and the dtd file)

2) appenders: Each appender is defined below, that is, the output. There are many categories, which are not mentioned here (which may cause pressure on understanding and interpretation, you may not be able to understand it at the beginning, which is equal to the white Lecture). First Look At This example. There is only one Console. These nodes are not just named, and the Console is the meaning of the output Console. Then we set some attributes for this output. Here we set PatternLayout to be the output format, which is basically the previous time, thread, level, logger name, log information, and so on, you can check their own syntax rules.

3) loggers define multiple logger types. These logger types are differentiated by name to configure different output for different logger types by referencing the logger defined above. Note that, the value referenced by appender-ref is the name of each appender above, rather than the node name.

  

7. name mechanism:(See: http://logging.apache.org/log4j/2.x/manual/architecture.html)

Cn. lsw. base. log4j2. hello, this name is actually passed through the preceding Hello. class. getName ();, We will generate a logger for this class in order to configure it separately. The above configuration basically means only cn. lsw. base. log4j2. hello, This logger outputs the trace information, that is, its log level is trace. Other logger inherits the root log configuration, and the log level is error, only logs of ERROR and above levels can be printed. If the name attribute of logger 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 logger name of log4j, not the java package, if you want to generate a logger named "myhello" for Hello, it cannot inherit from cn. lsw. base.

 

Someone will ask, Isn't he supposed to inherit the root configuration? Will it be output twice? We explained in the configuration file that if you set additivity = "false", it will not be output twice. Otherwise, let's look at the output below:

Here we will add a class for comparison:

Logger logger = LogManager. getLogger (Test. "Start program." = (! "Hello" logger. trace ("Exit program ."

Here, we need to change the configuration file to make it easier to compare. Is it the name of the first logger or cn. lsw. base. log4j2. hello, additivity is removed or changed to true (because the default value is true, so it can be removed). The second is to change the root level to info for observation.

Run Test to view the log output on the console:

2013-12-20 19:59:42.538 2013-12-20 19:59:42.541 2013-12-20 19:59:42.541 2013-12-20 19:59:42.542 2013-12-20 19:59:42.542 2013-12-20 19:59:42.542 2013-12-20 19:59:42.542 2013-12-20 19:59:42.542 2013-12-20 19:59:42.542 2013-12-20 19:59:42.542 2013-12-20 19:59:42.542 2013-12-20 19:59:42.542 2013-12-20 19:59:42.542 2013-12-20 19:59:42.542 2013-12-20 19:59:42.542 2013-12-20 19:59:42.543 2013-12-20 19:59:42.543 2013-12-20 19:59:42.543  ERROR cn.lsw.base.log4j2.Test - hello

It can be seen that the trace log of Test is not output, because it inherits the root log configuration and only outputs logs of the info level or above. Hello, logs of the trace and above levels are output, but each log is output twice. You can try to set the level of the first logger to error, so the level above error is also output twice. At this time, you only need to add additivity to false to avoid this problem.

Of course, you can make different configurations under the configuration file for each logger, or configure different logs under different packages through the inheritance mechanism. Because logger can write many songs.

The following is a slightly complex example:

                                                                                                                                                                                                                                    

Complexity is actually not complicated. This example mainly aims to talk about appenders.

Three appender, Console, File, and RollingFile are defined here. The meaning is basically clear. The second is to write the File, and the third is the log File of "loop, when the log file exceeds the threshold, a new log file is written.

The annotations in our configuration file are described in detail. So you can read it yourself. One of the more interesting ones is ThresholdFilter, a filter. In fact, each appender can define many filters, which is very useful. If you want to select the console to output only the categories above ERROR, you can use ThresholdFilter to set the level to ERROR. onMatch = "ACCEPT" onMismatch = "DENY" means that matching is acceptable, otherwise, we will reject the request directly. Of course there are other options, such as handing the request to other filters for processing. Let's take a look at the details.

Why add a configuration file like this? In fact, I feel very good about this configuration file. His practicality is as follows:

  8. A practical configuration file:

On the one hand, we use logs to record the program running information, troubleshoot errors, and so on. Sometimes we also like to use logs during debugging. Therefore, it seems inconvenient to log records in a mess. Therefore, I may have the following requirements:

1) I am debugging a class, so I don't want to output logs of other classes or packages. Otherwise, there will be a lot of content, you can modify the above root level to the highest level (or use ERROR for caution), and then add a logger configuration for the class, such as the setting in the first configuration file, set the level to trace, debug, and so on. Then we will give an appender-ref the appender that defines the File (three appender in total, remember ), the advantage of this appender is that the append attribute is false. In this way, the last log is cleared during each operation, so that the content of this file will not be added due to continuous debugging, it is easy to query, and the result is output to the console.

2) I have basically deployed the program and it will take a long time to run. I need to record the following logs. First, the console outputs all the information above the error level. Second, I want to have a file that outputs all the information above debug or info, similar to program record or something. Third, I want to output the information above ERROR to a separate file. If an ERROR occurs, I just need to check the configuration file and will not process too many logs, it seems that the headers are all big. How to do it is very simple.

> First, add a Console-type appender under the appenders and set the level to error by adding a ThresholdFilter. (Modify it directly in the appender of the configuration file Console)

> Next, add a File-type appender (or RollingFile or other File output types), set the level of ThresholdFilter to error, and set it to File, you should not have so many error logs and do not need to have multiple error-level log files. Otherwise, your program can be rewritten.

Here you can add an appender with the following content:

  

                                  

And reference it in a logger (such as root) in loggers (add this row to the root node as a sub-node ).

  

  

> Then, add an appender for the RollingFile and set the configuration file similar to the preceding one.

> Finally, configure the logger. However, if your logger also has a log-level configuration, if the level is above error, your appender will not output the error information.

Remember there is a commented out for loop in the Test class above? This is to configure the appender in the RollingFile in the configuration file. Cancel the annotation and run the agent once or several times to view the location of your output configuration file, how does he "RollingFile"? Here I will test it: (here you can change the size of <SizeBasedTriggeringPolicy size = "50 MB"/> to 2 MB, it is still slow to generate 50 MB logs. For convenience of observation! Set the level of ThresholdFilter in the Console to a higher level such as error. Otherwise, the Console outputs too many items)

  

The first part (marked as 1 in the figure) is the jar package I added;

The second part is the log File generated by the appender File. You will find that the logs in this File are overwritten many times.

The third part is the configuration file generated by the appender RollingFile. You can find that the app is created by default. when the log size exceeds 2 MB, the corresponding year-month folder will be generated, and the named log file will be compressed into a gz file, open the resource manager and find that the file is only 11 kb. After decompression, It is 2 MB.

Finally, I hope this tutorial will help you!

  

 

 

  

    

Related Article

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.