Log(logBack), thread, unit test(Junit)

Log

Log definition:

The computer is used to record all operating procedures or tools (errors, records, etc.)

The role of logs:

Just like a diary, it records information about program operations, the location of warnings, or when errors occur, so as to track specific data. It can also be conveniently recorded to specific locations, such as the console or files.

Common logging frameworks:

Date framework: Logback implementation based on Slf4j

Log level: Different levels display different information (the logs supported by different frameworks may be basically different)

Log level priority: (from low to high) (A

ALL: Display all log information

TRACE: Trace, specify the program running trajectory (generally not used), can display trace and logs above trace

DEBUG: debugging, the lowest log level in the application (self-developed software), used for program debugging, exposing running details, and can display debug and above logs

INFO: Information, when the program is running normally, information is recorded, and logs above info and info can be displayed.

WARN: Warning, the program can run, but an error may occur, logs with warning and above warning can be displayed.

ERROR: Error, program error, cannot be solved automatically, can display error and above error logs

FATAL: Fatal, irreparable error, able to display logs of fatal and fatal or above

OFF: Close all log information

(Note: Yellow content is the most commonly used)

Logback entry code implementation:

The logback logging framework is an example:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestLog {
    //Each class needs to have a date recorder
    private static Logger logger = LoggerFactory.getLogger("TestLog");

    public static void main(String[] args) {
        //Default debug

        //Display information at different log level levels
        logger.trace("Trace");
        logger.debug("debug");
        logger.info("information");
        logger.warn("warning");
        logger.error("error");
    }
}

Modify configuration file

Logback provides a core configuration file logback.xml (must be used in the src directory)

When recording logs, the logging framework reads the configuration information in the configuration file to record the log format. What specific configurations can be made?

1. You can configure whether the log output location is a file or the console
2. You can configure the format of log output
3. You can also configure log closing and opening, as well as which logs are output and which logs are not output.

  • As shown in the figure below, control whether the log is output to a file or to the console

  • As shown in the figure below, control the format of log output

    The log format is composed of some special symbols, and you can delete the parts you don’t want to see as needed. For example, if you don’t want to see the thread name, don’t use [%thread]. However, it is not recommended that students change these formats because these are very basic information in the log.

logback.xml source file code:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!--
        CONSOLE: Indicates that the current log information can be output to the console.
    -->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <!--Output stream object default System.out changed to System.err-->
        <target>System.out</target>
        <encoder>
            <!--Formatted output: %d represents the date, %thread represents the thread name, %-5level: the level displays 5 characters wide from the left
                %msg: log message, %n is the newline character -->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] %c [%thread] : %msg%n</pattern>
        </encoder>
    </appender>

    <!-- File is the output direction leading to the file -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
            <charset>utf-8</charset>
        </encoder>
        <!--Log output path-->
        <file>D:/log/itheima-data.log</file>
        <!--Specify log file splitting and compression rules-->
        <rollingPolicy
                class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!--Determine the file splitting method by specifying the compressed file name-->
            <fileNamePattern>D:/log/itheima-data-%i-%d{yyyy-MM-dd}-.log.gz</fileNamePattern>
            <!--File split size-->
            <maxFileSize>1MB</maxFileSize>
        </rollingPolicy>
    </appender>

    <!--
        1. Control the output of logs: for example, enable logs, cancel logs
    -->
    <root level="debug">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE" />
    </root>
</configuration>

Thread

Process: To run a piece of software in a computer, it requires a process

Thread: Within a program (process), the independently running unit is a thread.

Summary: A process can have multiple threads, which is called multi-thread development

Create thread:

Three ways:

Thread subclass

Runnable interface implementation class

Callable interface implementation class

Anonymous inner class

The specific code is as follows:

Thread subclass

Runnable interface implementation class

Callable interface implementation class

Anonymous inner class

Comparative summary of three ways to create threads:

Please see: Homepage -> Summary of java interview questions -> There are several ways to create a thread (must know)

Unit testing

The so-called unit test is to write test code to test the correctness of the smallest functional unit.

For example, we wrote a student management system with functions such as adding students, modifying students, deleting students, and querying students. To test these functions, we write code in the main method to test.

In order to make testing more convenient, some third-party companies or organizations provide very useful testing frameworks for developers to use. Here we introduce a Junit testing framework to students.

Junit is an open source tool developed by a third-party company for unit testing of code (IDEA has integrated the junit framework)

Junit

1. Implement the guide package

package Junit;

import org.junit.Test;

public class TestJunit {
    /**
     *Unit testing method requirements:
     * 1. Cannot be private, must be public
     * 2. Non-static, cannot be modified with the static keyword
     * 3. No return value void
     * 4. The method name is arbitrary
     * 5. No parameters
     */
    @Test
    public void info(){
        System.out.println("info");
    }

    @Test
    public void show(){
        System.out.println("show");
    }
}

Common annotations of Junit framework

Dear students, we just learned about the @Test annotation, which can be used to mark a method as a test method so that the test can start execution.

In addition to the @Test annotation, there are some other annotations. We need to know when the methods marked by other annotations are executed, and in what scenarios other annotations can be used.

Unit test assertion

Next, we learn the assertion mechanism of a unit test. The so-called assertion: It means that the programmer can predict the running results of the program and check whether the running results of the program are consistent with expectations.

We add a new test method in the StringUtil class

 public static int getMaxIndex(String data){
     if(data == null){
         return -1;
     }
     return data.length();
 }

Next, we write a test method in the StringUtilTest class

public class StringUtilTest{
    @Test
    public void testGetMaxIndex(){
       int index1 = StringUtil.getMaxIndex(null);
       System.out.println(index1);
        
       int index2 = StringUtil.getMaxIndex("admin");
       System.out.println(index2);
        
        //Assertion mechanism: predict the result of index2
        Assert.assertEquals("There is a bug inside the method",4,index2);
    }
}

operation result: