Home > Java > javaTutorial > body text

How to use Log4j log in Java

王林
Release: 2023-05-05 14:10:11
forward
2669 people have browsed it

Why use logs?

We know that a lot of information will be generated during the running process of the program. For example, at what time it was run, and what was the result of the run? In order for us to better understand the running status of the program, we can view it through the log. The log can be output on the console or output to a specified file. We will introduce it to you in detail in the following article.

Download:

Log4J is an open source project of Apache Company for log processing. Download address:

https://logging.apache.org/log4j/2.x/download.html

How to use Log4j log in Java

After the download is completed, We can get a package with the suffix name jre.

Detailed steps:

1. Open IDEA

to create a new project, then create a new lib package in the project and put the log4j.jar package into it.

How to use Log4j log in Java

Then create a class in src:

How to use Log4j log in Java

## Just follow the steps in the picture:

How to use Log4j log in Java

Just add the jre package here:

How to use Log4j log in Java

2. Create the log object

When the above operation is completed After that, you can create objects in the class:

Note: The Logger package selected here is a package from apache, be sure not to choose the wrong one here!

How to use Log4j log in Java

import org.apache.log4j.Logger;

public class logTest {

    public static void main(String[] args) {

        //导入对象:
        Logger log = Logger.getLogger(logTest.class);
        log.error("用于记录error级别的信息"); //记录严重错误
        log.warn("用于记录warn级别的信息");   //记录警告
        log.info("用于记录info级别的信息");   //记录信息
        log.debug("用于记录debug级别的信息"); //记录debug
    }
}
Copy after login

Then we need to create a configuration file:

Create a new file file, the file suffix must be properties

How to use Log4j log in Java

Then create a new file, the name can be set to: resources, and change the format to the following picture:

How to use Log4j log in Java

Then put the configuration file you just created into this Just inside the file:

How to use Log4j log in Java

We need to configure the following three most important information in log.properties:

  • Configure your What level of logs will the program record into the log file?

  • Specify the destination of the log output, whether to record the logs to the program's console (transient state) or somewhere on the disk. In the file (persistent storage)

  • Specify the output format of the log information output to the console or file, or in what format the log information is recorded.

The set template is as follows:

Copy it directly to log.properties:

# 1. Set the output level info, Info and higher levels can be recorded to the log file, but lower levels such as debug will not be recorded in the log file

# stdout is the destination of the set log record (the name can be chosen casually) To correspond)
log4j.rootLogger=info,stdout

#2. Set the destination of logging (ConsoleAppender records to the console)

log4j.appender.stdout=org.apache. log4j.ConsoleAppender

#3. Set the record format or style (System.err is red style, System.out is black style)

log4j.appender.stdout.Target=System.err
# Set the record format
#PatternLayout is laid out according to our custom rules (%d %l %m %n is the specified rule layout)
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %l %m %n

We can ignore this configuration information first. To complete the above configuration, let’s run the above first. That piece of code:

How to use Log4j log in Java

# If this appears, it means it is correct. Let’s rewrite a piece of code to see the function of this log:

import org.apache.log4j.Logger;

import java.util.Scanner;

public class test2 {
    public static void main(String[] args) {

        Logger logger = Logger.getLogger(test2.class);
        Scanner input = new Scanner(System.in);
        try{
            System.out.println("请输入除数:");
            int a = input.nextInt();
            logger.debug("bug:输入除数"+a);
            logger.info("info:输入除数"+a);
            System.out.println("请输入被除数:");
            int b = input.nextInt();
            logger.debug("bug:输入除数"+b);
            logger.info("info:输入除数"+b);
            int c = a/b;

            //把结果记录到日志文件中
            logger.debug("bug:结果"+c);
            logger.info("info:结果"+c);
            System.out.println("结果是:"+c);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }finally {
            System.out.println("程序结束!!");
        }
    }

}
Copy after login

This is a division operation, run it first and see the effect:

How to use Log4j log in Java

We found , every step we execute in the program is recorded in the log. Because the configuration file is set to output to the console, the log information is displayed directly on the console. If you need to output to a specified file, you need to configure it as follows:

How to use Log4j log in Java

Then run the division program:

How to use Log4j log in Java

There is no log information displayed on the console because it has been set to output to the specified file: According to the set path, we can see:

How to use Log4j log in Java

like this The time information, program name information, and information about what happened in the line of the program are all recorded. Of course, there are many more output formats, you can set them up as needed!

This is where Senior Xiaoying talks about Log4j logs. After completing these steps, a simple log record is completed. The following log output levels also need to be noted.

Log output level:

1.off: the highest level, used to turn off all logging
2.fatal indicates that each serious error time will cause the application to Exit of the program
3.error means that although an error event is sent, it still does not affect the operation of the system
4.warn indicates that a potential error situation will occur
5.info General users record the running process of the program
6.debug is generally used for debugging information records
7.all is the lowest level, used to open all log records

The above is the detailed content of How to use Log4j log in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template