Log components in Java-log4j

Source: Internet
Author: User
Tags log4j

1. Why use the Log component

LOG4J is an Apache open source project, it is a log operation package, by using log4j, you can specify the destination of the log information output, such as console, file, Cui component, NT Event recorder, and also control each log output format. In addition, by defining the level of log information, you can control the output of the log in a very granular manner, and most interesting of all, these features can be configured flexibly through a single configuration file without the need to modify the application code.

There are 3 purposes for outputting logs in an application:

    • Monitor the change of the variables in the code, and record the data periodically to the file for other applications to perform statistical analysis work;
    • Tracking code run-time trajectory, as the basis for future audit;
    • Act as a debugger in the integrated development environment to print debug information for the code to the file and console;

LOG4J consists of three major components:

    • Logger: Responsible for generating log, and can classify and filter the log information;
    • Appender: Defines the destination of the log information output, specifies where the log information should be exported, which can be console, file, network device, etc.
    • Layout: Specifies the output format of the log information;
2. Configuration steps

introduction of jar files;

Configure Src/log4j.properties

#通过根元素指定日志输出的级别, Destination #debug< Info < warn <Errorlog4j.rootlogger=debug,console,file############# #日志输出到控制台 ################# #日志输出到控制台使用的API类log4j. Appender.console=org.apache.log4j.consoleappender# The format of the log output log4j.appender.console.layout=Org.apache.log4j.PatternLayoutlog4j.appender.console.layout.ConversionPattern=%d%p%c.%m ()-%m%n############# #日志输出到文件 ################ #log4j. Appender.file=org.apache.log4j.rollingfileappender# Specifies the path to the log file Log4j.appender.file.File=.. /logs/mylog.log# Specifies the maximum size of the log file Log4j.appender.file.MaxFileSize=1024kb# The maximum number of log files generated Log4j.appender.file.MaxBackupIndex=10#日志输出格式log4j. Appender.file.layout=Org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern=%d%p%c.%m ()-%m%n
    • The Appender component can specify one of the following five destinations:

1.org.apache.log4j.consoleappender (console)
2.org.apache.log4j.fileappender (file) "can only output a log file, not recommended"
3.org.apache.log4j.dailyrollingfileappender (Generate a log file every day)
4.org.apache.log4j.rollingfileappender (creates a new file when the file size reaches the specified size)
5.org.apache.log4j.writerappender (send log information in stream format to any specified location)

A. Consoleappender Options
Threshold=warn: Specifies the lowest level of output for log messages.
Immediateflush=true: The default value is true, meaning that all messages will be output immediately.
Target=system.err: By default: System.out, specify output console
B. Fileappender Options

Threshold=warn: Specifies the lowest level of output for log messages.

Immediateflush=true: The default value is true, meaning that all messages will be output immediately.

File=mylog.txt: Specifies the message output to the Mylog.txt file.
Append=false: The default value is True, the message is added to the specified file, and false refers to overwriting the message with the specified file content.

C.dailyrollingfileappender Options
Threshold=warn: Specifies the lowest level of output for log messages.
Immediateflush=true: The default value is true, meaning that all messages will be output immediately.
File=mylog.txt: Specifies the message output to the Mylog.txt file.
Append=false: The default value is True, the message is added to the specified file, and false refers to overwriting the message with the specified file content.

Datepattern= '. ' YYYY-WW: Scrolls a file once a week, which results in a new file every week. You can also specify monthly, weekly, Days, hours, and minutes. The corresponding format is as follows:

1) '. ' YYYY-MM: Monthly
2) '. ' YYYY-WW: Weekly
3) '. ' YYYY-MM-DD: Every day
4) '. ' Yyyy-mm-dd-a: two times a day
5) '. ' YYYY-MM-DD-HH: Per hour
6) '. ' YYYY-MM-DD-HH-MM: Per minute
D.rollingfileappender Options
Threshold=warn: Specifies the lowest level of output for log messages.
Immediateflush=true: The default value is true, meaning that all messages will be output immediately.
File=mylog.log: Specifies the message output to the Mylog.txt file.
Append=false: The default value is True, the message is added to the specified file, and false refers to overwriting the message with the specified file content.

MAXFILESIZE=100KB: The suffix can be kb, MB, or GB. When the log file reaches this size, it will automatically scroll to move the original content to the Mylog.log.1 file.

maxbackupindex=2: Specifies the maximum number of scroll files that can be produced.

    • The layout component can specify one of the following four destinations:

1.org.apache.log4j.htmllayout (layout in HTML table) contains options: locationinfo=true: Default value is false, output Java file name and line number title=my app file: Default value is log4j Log Messages

2.org.apache.log4j.patternlayout (the flexibility to specify layout mode) contains options: conversionpattern=%m%n: Specifies how the specified message is formatted

3.org.apache.log4j.simplelayout (contains level and information strings for log information)
4.org.apache.log4j.ttcclayout (contains information about the time, thread, category, etc.) of the log

    • The meaning of several symbols in the log Information format:

-X: Left-aligned when the information is output;
%p: Output log information priority, i.e. Debug,info,warn,error,fatal,
%d: the date or time of the output log time, the default format is ISO8601, can also be specified after the format, such as:%d{yyy MMM dd hh:mm:ss,sss}, output similar: October 18, 2002 22:10:28,921
%r: The number of milliseconds to output the log information from the application boot to output
%c: The class in which the output log information belongs, usually the full name of the class in which it is located
%t: Output The name of the thread that generated the log event
%l: The location of the output log event, which corresponds to the combination of%c.%m (%f:%l), including the class name, the thread that occurred, and the number of rows in the code. Example: Testlog4.main (testlog4.java:10)
%x: The NDC (nested diagnostic environment) associated with the output and current line threads, especially for multi-client multithreaded applications such as Java Servlets.
Percent: Output a "%" character
%F: The name of the file where the output log message was generated
%l: Line numbers in the output code
%M: The specified message in the output code, resulting in the log specific information
%n: Output a carriage return line break, Windows platform is "\ r \ n", Unix platform for "\ n" Output log information line-wrapping

%M the name of the method represented
can be in % a modifier is added to the pattern character to control its minimum width, maximum width, and text alignment. such as:
1)%20c: Specifies the name of the output category, the minimum width is 20, if the category name is less than 20.
2)%-20c: Specify the name of the output category, the minimum width is 20, if the category name is less than 20, the "-" number specifies left-aligned.
3)%.30c: Specify the name of the output category, the maximum width is 30, if the category name is greater than 30, will be the left more than the character of the cut off, but less than 30, there will be no spaces.
4)%20.30c: If the category name is less than 20, fill in the blanks, and right-aligned, if its name is longer than 30 characters, it is exported from the left hand-sold characters are truncated.

3. Using the Log component
        Log log = Logfactory.getlog (Demo1.  Class);        Log.debug ("commissioning");        Log.info ("Information tip");        Log.warn ("Warning");        Log.error ("Exception");

Log components in Java-log4j

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.