[Yugong series] use of 79 log4j log in Java Teaching Course in January 2022

preface

Like the black box of the aircraft, the log is used to record the operation information of the website server, or simply to record what pages in the server are accessed by whom and when. For example, if you visit Huawei's website once, the log of the website server will record that the visitors from a certain IP index the web page "/ index.html" at a certain time and at a certain moment. Of course, the website server log also records many other contents, which can help us analyze the traffic of the website and the behavior of visitors on the website.

1, Log

1. General

  • summary

    The log in the program can be used to record the bit by bit when the program is running. And can be stored permanently.

  • The difference between log and output statement

    Output statementLog technology
    Cancel logThe code needs to be modified, and the flexibility is poorThere is no need to modify the code, which is more flexible
    output locationConsole onlyLog information can be written to a file or database
    MultithreadingAnd business code are in the same threadMulti thread logging does not affect the performance of business code

2. Log architecture and Log4J

  • Architecture

  • Log4J

    Log4j is an open source project of Apache.

    By using Log4j, we can control the destination of log information delivery to console, file and other locations.

    We can also control the output format of each log.

    By defining the level of each log information, we can control the log generation process in more detail.

    The most interesting thing is that these can be flexibly configured through a configuration file without modifying the application code.

  • Apache Foundation

    The Apache Software Foundation (ASF) is a non-profit organization established to support open source software projects.

3. Introductory cases

  • Use steps

    1. Import the related jar package of log4j
    2. Write log4j configuration file
    3. Get the object of the log in the code
    4. Log information according to level settings
  • Code example

    // The configuration file of log4j is named log4j Properties in the src root directory
    log4j.rootLogger=debug,my,fileAppender
    
    ### direct log messages to my ###
    log4j.appender.my=org.apache.log4j.ConsoleAppender
    log4j.appender.my.ImmediateFlush = true
    log4j.appender.my.Target=System.out
    log4j.appender.my.layout=org.apache.log4j.PatternLayout
    log4j.appender.my.layout.ConversionPattern=%d %t %5p %c{1}:%L - %m%n
    
    # fileAppender��ʾ
    log4j.appender.fileAppender=org.apache.log4j.FileAppender
    log4j.appender.fileAppender.ImmediateFlush = true
    log4j.appender.fileAppender.Append=true
    log4j.appender.fileAppender.File=D:/log4j-log.log
    log4j.appender.fileAppender.layout=org.apache.log4j.PatternLayout
    log4j.appender.fileAppender.layout.ConversionPattern=%d %5p %c{1}:%L - %m%n
    
    // Test class
    public class Log4JTest01 {
    
        //Use the api of log4j to get the log object
        //Disadvantages: if we change the implementation class of log in the future, the following code needs to be changed accordingly
        //Not recommended
        //private static final Logger LOGGER = Logger.getLogger(Log4JTest01.class);
    
        //Use the api in slf4j to get the log object
        //Benefit: if we change the implementation class of log in the future, the following code does not need to be modified
        //Recommended use
        private static  final Logger LOGGER = LoggerFactory.getLogger(Log4JTest01.class);
    
        public static void main(String[] args) {
            //1. Import jar package
            //2. Prepare configuration file
            //3. Get the log object in the code
            //4. Set the log information according to the log level
            LOGGER.debug("debug Level log");
            LOGGER.info("info Level log");
            LOGGER.warn("warn Level log");
            LOGGER.error("error Level log");
        }
    }
    

4. Detailed explanation of configuration file

  • Three cores

    • Loggers log level

      There are five common levels of Loggers components in this system: DEBUG, INFO, WARN, ERROR and FATAL.

      DEBUG < INFO < WARN < ERROR < FATAL.

      Log4j has a rule: only log information with a level not lower than the set level is output.

    • Where the Appenders log is to be output

      Output logs to different places, such as Console, Files, etc.

      • org.apache.log4j.ConsoleAppender
      • org.apache.log4j.FileAppender (file)
    • Layouts log output format

      You can specify the format of log output according to your preferences

      Common layout managers:

      ​ org.apache.log4j.PatternLayout (layout mode can be specified flexibly)

      ​ org.apache.log4j.SimpleLayout (contains the level and information string of log information)

      org.apache.log4j.TTCCLayout (including log generation time, thread, category and other information)

  • Configure root Logger

    • format

      log4j.rootLogger = log level, appenderName1, appenderName2

    • log level

      OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL or custom level.

    • appenderName1

      Specifies where the log information should be output. Multiple output destinations can be specified at the same time, separated by commas.

      For example: log4j rootLogger=INFO,ca,fa

  • Common options for ConsoleAppender

    • ImmediateFlush=true

      Indicates that all messages will be output immediately. If it is set to false, it will not be output. The default value is true.

    • Target=System.err

      The default value is system out.

  • FileAppender common options

    • ImmediateFlush=true

      Indicates that all messages will be output immediately. If it is set to false, it will not be output. The default value is true

    • Append=false

      true indicates that the message is added to the specified file, and the original message is not overwritten.

      false overwrites the message with the specified file content. The default value is true.

    • File=D:/logs/logging.log4j

      Specifies that the message is output to logging Log4j file

  • Common options for PatternLayout

    • ConversionPattern=%m%n

      Sets the format in which messages are displayed

5. Application in the project

  • step

    1. Import related dependencies
    2. Copy the properties configuration file in the data to the src directory
    3. Get the object of the log in the code
    4. Log information according to level settings
  • code implementation

    @WebServlet(urlPatterns = "/servlet/loginservlet")
    public class LoginServlet implements HttpServlet{
    
        //Get the object of the log
        private static final Logger LOGGER = LoggerFactory.getLogger(LoginServlet.class);
    
        @Override
        public void service(HttpRequest httpRequest, HttpResponse httpResponse) {
           //handle
            System.out.println("LoginServlet Login request processed");
    
            LOGGER.info("The login request has now been processed and is ready to respond to the browser");
    
           //response
            httpResponse.setContentTpye("text/html;charset=UTF-8");
            httpResponse.write("Login successful");
        }
    }
    

Keywords: Java Apache

Added by BradZynda on Wed, 26 Jan 2022 02:08:31 +0200