Common log4j usage

Source: Internet
Author: User

I have been using logs encapsulated by others for some time. I feel very curious when I have configured logs. Next we will record the common usage of using log4j to process logs.

As for what log4j is, I don't know what it is, and I don't think it is necessary to go too deep for the moment. I only know that it is a good choice to process logs.

Game starts

References

1) official PDF document

2) Configure log4j (and details)

3) Log Level of log4j

Dependent jar package

1) log4j-api-2.0.2.jar

2) log4j-core-2.0.2.jar [d]

Main classes

1) Logger

Look at the name will know what is done, is to rely on him to record the log, but the specific implementation class has been encapsulated in the log4j-core-2.0.2.jar, we only need to configure his Processing Method

Commonly used methods include Info (Message), warn (Message), and error (Message );

2) logmanager

Use the static logmanager. getlogger (name); method to obtain the defined logger. The name passed here is related to the configuration file

3) config

Two types of log4j2. xml and log4j. properties are commonly used in configuration files;

The configuration file should be placed under classpath, which is generally placed under SRC.

(Log4j2 can only be configured in XML and JSON format)

4) appender

Configuration in the configuration file, indicating the log Display Media

  

1 Org. apache. log4j. consoleappender (console), 2 Org. apache. log4j. fileappender (file), 3 Org. apache. log4j. dailyrollingfileappender (a log file is generated every day), 4 Org. apache. log4j. rollingfileappender (a new file is generated when the file size reaches the specified size), 5 Org. apache. log4j. writerappender (send log information to any specified place in stream format)

Presentation Format (patternlayout is used only currently, and most of them are used)

1 Org. apache. log4j. htmllayout (layout in HTML form), 2 Org. apache. log4j. patternlayout (you can flexibly specify the layout mode), 3 Org. apache. log4j. simplelayout (Level and information string containing log information), 4 Org. apache. log4j. ttcclayout (including the log generation time, thread, category, and so on)

  

Attribute Configuration

Console option Threshold = Debug: specify the minimum output level of log messages. Immediateflush = true: the default value is true, meaning that all messages will be output immediately. Target = system. Err: system. Out by default. Specify the output console fileappender option Threshold = debuf: specify the minimum output level of log messages. Immediateflush = true: the default value is true, meaning that all messages will be output immediately. File1_mylog.txt: refers to the output to the mylog.txt file. Append = false: The default value is true. To add a message to a specified file, false means to overwrite the specified file content. Rollingfileappender option Threshold = Debug: Specify the lowest level of log message output. Immediateflush = true: the default value is true, meaning that all messages will be output immediately. File1_mylog.txt: refers to the output to the mylog.txt file. Append = false: The default value is true. To add a message to a specified file, false means to overwrite the specified file content. Maxfilesize = 100kb: The suffix can be kb, MB, or GB. When the log file reaches this hour, it will automatically scroll, moving the original content to the mylog. log.1 file. Maxbackupindex = 2: specify the maximum number of rolling files that can be generated.

5) level

Logger behaviors are classified. Specific levels include off, fatal, error, warn, info, debug, trace, and all. We recommend that you use only four levels of log4j. The priority ranges from high to low: error, warn, info, and debug. By defining the level here, you can control the switch to the corresponding level of log information in the application. For example, if the info level is defined here, all debug-level logs in the application will not be printed. The program prints logs higher than or equal to the set level. The higher the set log level, the fewer printed logs. If the setting level is info, logs with a higher priority than or equal to Info level (such as info, warn, and error) can be output. logs with a lower priority level such as debug will not be output. This article from the Linux community website (www.linuxidc.com) original link: http://www.linuxidc.com/Linux/2012-09/70120.htm

6) Pattern

Meanings of several symbols in log information format:-X: Left alignment for output of X information; % P: Priority of output log information, that is, debug, info, warn, error, fatal, % d: date or time of the log output time point. The default format is iso8601. You can also specify the format after it, for example: % d {YYY Mmm dd hh: mm: SS, SSS}, output is similar to: October 18, 2002 22:10:28, 921% R: The number of milliseconds that the application started to output the log information % C: the category of the output log information, this is usually the full name of the Class % T: name of the thread that outputs the log event % L: location where the log event is output, equivalent to % C. % m (% F: % L) combination, including the category name, the thread that occurs, and the number of lines in the code. Example: testlog4.main (testlog4.java: 10) % x: Output NDC (nested Diagnostic Environment) associated with the current thread, especially in applications with multiple clients and multithreading such as Java Servlets. %: Output A "%" character % F: name of the file where the output Log message was generated % L: Row Number % m in the output code: output the message specified in the Code, specific log information % N: Output A carriage return line break, Windows platform is "/R/N ", on UNIX platforms, for "/N" output log information, you can add modifiers between % and mode characters to control the minimum width, maximum width, and text alignment. For example: 1) % 20c: specify the name of the output category. The minimum width is 20. If the category name is smaller than 20, it is right aligned by default. 2) %-20C: specify the name of the output category. The minimum width is 20. If the category name is smaller than 20, the "-" sign specifies the left alignment. 3) %. 30C: specify the name of the output category. The maximum width is 30. If the category name is greater than 30, the extra characters on the left will be truncated, but there will be no spaces if the value is less than 30. 4) % Category 30C: If the category name is less than 20, fill in spaces and align right. If the category name is longer than 30 characters, it will be truncated from the long-distance output on the left.
Always be coding

1) log4j2. xml

  

1 <? XML version = "1.0" encoding = "UTF-8"?> 2 <configuration status = "Warn"> 3 <appenders> 4 <console name = "console" target = "system_out"> <! -- Console output --> 5 <patternlayout pattern = "% d {hh: mm: Ss. SSS} [% T] %-5 level % logger {36}-% MSG % N "/> 6 </Console> 7 <file name =" file "> <! -- File output --> 8 <patternlayout pattern = "% d {yyyy-mm-dd hh: mm: SS}-% MSG % N "/> 9 </File> 10 </appenders> 11 <loggers> 12 <root level =" error "> <! -- Root-level log, level is error --> 13 <appenderref ref = "console"/> 14 </root> 15 <logger name = "mylogger" level = "info"> <! -- Custom log. The level is info. In the code, use logmanager. getlogger ("mylogger") to obtain --> 16 <appenderref ref = "file"/> <! -- Specify the file display mode --> 17 </logger> 18 </loggers> 19 </configuration>

2) log4j. Properties

1 # Root-level logger 2 log4j. rootlogger = info 3 # configure the console appender 4 log4j. appender. stdout = org. apache. log4j. leleappender 5 log4j. appender. stdout. target = system. out 6 log4j. appender. stdout. layout = org. apache. log4j. patternlayout 7 log4j. appender. stdout. layout. conversionpattern = % d {absolute} % 5 P % c {1}: % L-% m % N 8 # configuration file appender 9 log4j. appender. D = org. apache. log4j. fileappender10 log4j. appender. d. file =/logs/log. log11 log4j. appender. d. append = true12 log4j. appender. d. layout = org. apache. log4j. patternlayout13 log4j. appender. d. layout. conversionpattern = %-d {yyyy-mm-dd hh: mm: SS} [% T: % R]-[% P] % m % N14 # custom logger, logger configuration rules: log4j. logger. $ {loggername} = level, appender1, appender2 .... 15 log4j. logger. mylogger = level, d

3) log level relationship

What does Root-level log mean? Logs have a parent-child relationship like a class. rootlogger is the parent level of all logger. logger. a. B And log4j. logger. A and two logger, then a is. what is the use of B's parent level? Like the constructor method, the parent-level method is also called when the sub-level logger method is executed.

4) Code call

 1 package com.apache.log4j; 2  3 import org.apache.logging.log4j.LogManager; 4 import org.apache.logging.log4j.Logger; 5  6 public class LogWriter { 7     public static void main(String[] args) { 8         Logger logger = LogManager.getRootLogger(); 9         logger.error("hello");10     }11 }
To be continued ......

Common log4j usage

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.