LOG4J Study Notes

Source: Internet
Author: User

(i) The three main components of log4j: Loggers, Appenders, and Layouts, which work together to enable developers to record messages based on the type and level of messages, and to control the output format and location of messages during the program's run time.

1. Logger: Logger, responsible for most of the work of logging, is a core component.

2. Appender: The output destination of log information, responsible for the output control of log records.

3. Layout: Log formatter, responsible for formatting the output of the Appender.

Their diagram is as follows:

(ii) The level of the log:

The log levels in log4j are from low to High: all < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF, they are defined in

Org.apache.log4j.Level class , the log level is usually set in the log configuration file (as described later in the Log4j.properties file ).

OFF: It has the highest log level, indicating that no log is logged.

FATAL: Indicates a serious error that causes the application to exit.

Error: Indicates errors that can be corrected in general and does not affect the continuation of the application.

WARN: Information for the warning level.

Info: The required information record for the application execution.

Debug: Logging for easy debugging.

Trace: The log record of the program code execution trajectory.

All: The lowest level and all log information will be logged.

To implement these log levels, we need to implement log requests by calling the Logger method, which is commonly used in the following ways: Debug (), info (), warn (), error (), Fatal ().

(iii) Use cases of log4j

1. Import the development package: Log4j-1.2.17.jar

2. Define an instance variable of Logger in a program that requires logging, as a general practice:

private static final Logger Logger = Logger.getlogger (Xxx.class);

3. Call the appropriate log request method in the program.

4. Write the configuration file to illustrate how and when the log is displayed (create a log4j.properties file under SRC)

(1) first create Appenders

Log4j.appender.a1=org.apache.log4j.consoleappender

Indicates that a appender is created with the name A1 and the output policy is Org.apache.log4j.ConsoleAppender (the class can be found in the LOG4J API)

(2) Description of the log display layout

Log4j.appender.a1.layout=org.apache.log4j.patternlayout

Shows the layout of the Appender with the word A1, and the default layout used here is Patternlayout

(3) Description of the format to complete the display of the log

LOG4J.APPENDER.A1.LAYOUT.CONVERSIONPATTERN=%-4R%-5p [%t]%37c%3x-%m%n

The results shown in the console are as follows ( where the numbers in%-4r%-5p represent the interval between information ):

LOG4J offers the following types of layout:

Org.apache.log4j.HTMLLayout (Layout in HTML table Form)

Org.apache.log4j.PatternLayout (flexibility to specify layout mode)

Org.apache.log4j.SimpleLayout (contains level and information strings for log information)

Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, etc.) of the log

log4j formats the log information in a print format similar to the printf function in C, with the following printing parameters:

%M: The message specified in the output code
%p: Output priority, i.e. Debug,info,warn,error,fatal
%r: The number of milliseconds to output the log information from the application boot to output
%c: The class that the output belongs to, which is usually the full name of the class
%t: Output The name of the thread that generated the log event
%n: Output a carriage return line break, Windows platform is "\ r \ n", Unix platform is "\ n"
%d: the date or time of the output log time, the default format is ISO8601, or the format can be specified later,

For example:%d{yyy MMM dd hh:mm:ss,sss}, output similar: October 18, 2002 22:10:28,921
%l: The location where the output log event occurs, including the class name, the thread that occurred, and the number of rows in the code. Example: Testlog4.main (testlog4.java:10)

(4) When to output the log

Log4j.rootlogger=debug, A1 (DEBUG log level, A1 represents Appender)

Rootlogger represents Logge R for the root directory, and classpath for each project is the root directory. Indicates that a A1 is output whenever there is a log that is greater than or equal to the debug level.

LOG4J.LOGGER.LOG4J.DAO=DEBUG,A1

indicates that a class that is injected with logger logger = Logger.getlogger (xx.class) will output the log as long as it is found in the Log4j.dao package

5. The case code is as follows:

Catalog structure of the project:

configuration file (log4j.properties) Information:

log4j.appender.a1=org.apache.log4j.consoleappenderlog4j.appender.a1.layout=org.apache.log4j.patternlayoutlog4j.appender.a1.layout.conversionpattern=%-4r%-5p%d{yyyy-MM-dd HH:mm:ss}[%t]%37c%3x-%m%n# use Fileappender to output the log to a file #log4j.appender.fout=org.apache.log4j.fileappender# generates a new file by date #log4j.appender.fout=org.apache.log4j.dailyrollingfileappender#log4j.appender.fout.datepattern=‘.‘ yyyy-mm-dd-hh-mm# generates a new file by log file size log4j.appender.fout=org.apache.log4j.rollingfileappenderlog4j.appender.fout.maxfilesize=10#产生新文件时, mark the index of the new file log4j.appender.fout.maxbackupindex=50log4j.appender.fout.layout=org.apache.log4j.patternlayout# usually in actual project development, we are using a relative path. The usual method is to set the path to the System.setproperty () method # and then ${key} to get the value in System.setproperty () log4j.appender.fout.file=${log_dir}/file.loglog4j.appender.fout.layout.conversionpattern=%-4r%-5p [%t] %37c%3x-%m%n# Represents all of the output #log4j.rootlogger=debug that use logging under Classpath, a1# creates a logger named Test, which is name-based access, which is used in the class where you want to log records # Logger Logger = Logger.getlogger ("Test") to create Logger, but it is not recommended to use this way #log4j.logger.test=warn,fout# Indicates that a class that is injected with logger logger = Logger.getlogger (xx.class) will output the log as long as it is found in the Log4j.service package Log4j.logger.log4j.service=warn ,foutlog4j.logger.log4j.dao=debug,a1          

Classes in DAO Packages:

package Log4j.dao; Import Org.apache.log4j.logger; Public class Userdao { Private static final Logger Logger = Logger.getlogger ( Userdao. class); public void Loginfo () { Logger.debug ("Debug---user Information" ); Logger.warn ("Warn---warning message" ); }} 

Code in the Service pack:

Package Log4j.service; import Org.apache.log4j.logger; Public class UserService { private static final Logger Logger = Logger.getlogger (Userservice. Class); public void Loginfo () { Logger.debug ("Debug---user Information" ); Logger.warn ("Warn---warning message" ); }} 

Test the code in the package:

PackageLog4j.test;ImportLog4j.dao.UserDao;ImportLog4j.service.UserService;ImportOrg.junit.Test;PublicClasstestlog4j {@Testpublic void Testone () { Userdao DAO = new Userdao (); Dao.loginfo ();} @Test public void Testservice () { // Set the action relative to the path, corresponding to the configuration file: log4j.appender.fout.file=${ Log_dir}/file.log String uri = this.getclass (). getClassLoader (). GetResource ("" ). GetPath (); URI = Uri.replaceall ("bin/", "Log" ); System.setproperty ("Log_dir" , URI); System.out.println (URI); UserService service = new UserService (); Service.loginfo (); }}

Log4j Learning Notes

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.