Add log4j Log in Java code

Source: Internet
Author: User

1. Get the Recorder

Using log4j, the first step is to get the logger, which will be responsible for controlling the log information. Its syntax is:

public static Logger GetLogger (String name),

The logger is obtained by the specified name and, if necessary, a new logger is created for the name. Name generally takes the names of this class, such as:

static Logger Logger = Logger.getlogger (ServerWithLog4j.class.getName ());

2. Read the configuration file

When the logger is obtained, the second step configures the LOG4J environment with the following syntax:

1. Use the default log4j environment automatically and quickly.
Basicconfigurator.configure ();

2. Read the configuration file written using the Java properties file.
Propertyconfigurator.configure (String configfilename);

3. Read the configuration file in XML form.
Domconfigurator.configure (String filename);

4. Adding configuration information

Simplelayout simplelayout = new Simplelayout ();

try {
Fileappender FA = new Fileappender (simplelayout, "Test.log");
Logger.addappender (FA);
Logger.setlevel (Level.error);

Logger.error (Object obj);
} catch (IOException E1) {
//...
}

Choose one of four options

3. Inserting record information (formatting log information)

When the two necessary steps are completed, you can easily insert a logging statement with different priority levels into any place you want to log, with the following syntax:

Logger.debug (Object message);
Logger.info (Object message);
Logger.warn (Object message);
Logger.error (Object message);

Add log4j Log in Java code

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.