Python interface automated testing – logging

Log levels of the logging module: There are 5 log levels from low to high as follows. The purpose is that when you assign a logger to a python function, you need to mark the log level yourself (will be used later)

debug (debug level): the lowest severity level and the most detailed log information, often used for problem diagnosis

info (minor level): The severity is second only to DEBUG, and the information details are also second only to DEBUG. Usually only key node information is recorded to confirm whether everything is working as we expected.

warning (warning level): Information logged when something unexpected happens (for example, disk free space is low), but the application is still running normally.

error (error level): Information logged when some functionality is not functioning properly due to a more serious problem.

critical (serious error level): information recorded when a serious error occurs that prevents the application from continuing to run.

Four major components of python-logging:

logger: logger, provides an interface for direct use by application code

handler: processor, used to send log records to the specified destination

formater: formatter, used to define the output format of log information

filter: filter, filter log content

Writing the first logger:

import logging
 
# Create a logger: logging_name (logger name, you can write it casually), a logger can have multiple processors, and each processor can have its own different formatters and filters
logger = logging.getLogger('logging_name')
 
# Set the log output level. If not set, the default warning level will be used. That is, only when the log level is warning or above, the log will be printed. Otherwise, it will not be printed. Generally speaking, it needs to be set to debug to print all levels.
logger.setLevel(logging.DEBUG)
 
#Create processor:
sh = logging.StreamHandler()
 
# Create formatter: log time %(asctime)s, file name %(filename)s, line %(lineno)d, log level %(levelname)s, event content %(message)s
ft = logging.Formatter(fmt='Log time: %(asctime)s\\
File name: %(filename)s at line %(lineno)d\\
Log level: %(levelname)s\ nEvent content: %('
                           'message)s\\
', datefmt='%Y year %m month %d day %X')
 
# Add processor to logger
logger.addHandler(sh)
 
# Add the set formatter to the processor
sh.setFormatter(ft)
 
# Output log information. The event content needs to be written by yourself. In which file this code is placed, the error location will be displayed in which file.
logger.debug('Event content')
 
Execution results>>>
Log time: February 5, 2023 17:52:25
File name: test_003.py on line 23
Log level: DEBUG
Event content: Event content
Now I have also found a lot of test friends and created a communication group to share technology, sharing a lot of technical documents and video tutorials we collected.
If you don’t want to experience the feeling of not being able to find resources when studying on your own, having no one to answer your questions, and persisting for a few days before giving up.
You can join us to communicate. And there are many technical experts who have made certain achievements in automation, performance, security, test development, etc.
Share their experience, and also share many live lectures and technical salons
You can learn for free! Focus on it! Open source! ! !
QQ group number: 110685036

The above describes the simple creation of a logger. The following demonstrates how to integrate the logger into automation

First, we need to encapsulate the above “linear logger”, as follows, I encapsulate it into a class, and then remove the line of code that outputs the log, otherwise the error will always be located in the log function file.

import logging
class Log:
    def getlog(self):
        # Create a logger: logging_name (logger name, you can write it casually), a logger can have multiple processors, and each processor can have its own different formatters and filters
        logger = logging.getLogger('logging_name')
        # Set the log output level. If not set, the default warning level will be used. That is, only when the log level is warning or above, the log will be printed. Otherwise, it will not be printed. Generally speaking, it needs to be set to debug to print all levels.
        logger.setLevel(logging.DEBUG)
        #Create processor:
        sh = logging.StreamHandler()
        # Create formatter: log time %(asctime)s, file name %(filename)s, line %(lineno)d, log level %(levelname)s, event content %(message)s
        ft = logging.Formatter(fmt='Log time: %(asctime)s\\
File name: %(filename)s at line %(lineno)d\\
Log level: %(levelname)s\ nEvent content: %('
                                   'message)s\\
', datefmt='%Y year %m month %d day %X')
        # Add processor to logger
        logger.addHandler(sh)
        # Add the set formatter to the processor
        sh.setFormatter(ft)
        return logger

As follows, I defined a test case and a public function

def comparison(da):
    if da in '中文':
        return 'The function was executed successfully, it is Chinese'
 
# Test module
class TestC:
    # test case
    def test001(self):
        print(comparison(1))
 
TestC().test001()

As follows, I defined a test case and a public function comparison. The function of the public function is to enter “Chinese” and the execution will be successful. If you enter a number, an error will be reported.

def comparison(da):
    if da in '中文':
        return 'The function was executed successfully and it is Chinese'
 
# Test module
class TestC:
    # test case
    def test001(self):
        print(comparison(1))
 
TestC().test001()

My idea is very simple, I just want to add the logger to the comparison function. If an error is reported, I want to know its error time, error file, error line, error level, and error content. If successful, I also need to know its time, file, line, level, and content. How to achieve? It’s very simple, just transform the public function, as follows

# First import the log function
from test_001 import Log
 
def comparison(da):
 
    try:
        if da in '中文':
            # Success case
            Log().getlog().info(f' is executing the comparison function, there is no error yet, the comparison value is {da}: Chinese')
            return 'The function was executed successfully and it is Chinese'
    exceptException:
        # Error reporting situation
        Log().getlog().error(f' is executing comparison function, type comparison error, comparison value is {da}: Chinese')
 
# Test module
class TestC:
    # test case
    def test001(self):
        comparison(1)
 
 
TestC().test001()
 
 
Execution results>>>
Log time: February 5, 2023 17:49:29
File name: test_002.py on line 13
Log level: ERROR
Event content: The comparison function is being executed, the type comparison is wrong, the comparison value is 1: Chinese

logging – log written to txt file

As shown below, the only change is the code marked in orange

import logging
 
 
class Log:
    # Logger
    def getlog(self, log_path):
        """
        :param log_path: The path where the log input file is located. It is recommended that the file be in txt format. If the file does not exist, it will be automatically created.
        :return:
        """
 
        #Create logger: logging_name (logger name, you can write it casually)
        logger = logging.getLogger('logging_name')
 
        #Filter: Set log output level
        logger.setLevel(logging.DEBUG)
 
        #Create formatter: log time %(asctime)s, file name %(filename)s, line %(lineno)d, log level %(levelname)s, event content %(message)s
        ft = logging.Formatter(fmt='Log time: %(asctime)s\\
File name: %(filename)s at line %(lineno)d\\
Log level: %(levelname)s\ nEvent content: %('
                                   'message)s\\
', datefmt='%Y year %m month %d day %X')
 
        # Set file format
        handler = logging.FileHandler(log_path, encoding='UTF-8')
        handler.setFormatter(ft)
 
        # Add processor to logger
        logger.addHandler(handler)
 
        # Return the log outputter. logger logger, log_level log level, content log content
        return logger

How to use it? As follows, the orange changes

# First import the log function
from test_001 import Log
 
 
def comparison(da):
    try:
        if da in '中文':
            # log.txt: The path of the log file. If the file does not exist, it will be added automatically.
            Log().getlog('log.txt').debug(f' is executing the comparison function, there is no error yet, the comparison value is {da}: Chinese')
            return 'The function was executed successfully, it is Chinese'
    exceptException:
        # log.txt: The path of the log file. If the file does not exist, it will be added automatically.
        Log().getlog('log.txt').debug(f' is executing comparison function, type error, comparison value is {da}: Chinese')
 
 
# Test module
class TestC:
    # test case
    def test001(self):
        comparison(1)
 
 
TestC().test001()

After execution, there is no log output content on the console, and the content is output to the log.txt file, as follows.

Summary:

The above are the instructions for using the log module – logging. The difficulty of the log module is not in the code, but in the log setting point, that is, where is the best place to implant the log. The implantation function of the logger is best to be public. And the places where errors are most likely to be reported, just like the places where surveillance cameras are most likely to have troubles, so that problems can be quickly located.

In fact, in my projects, the function of writing logs to files is generally not used. I just input and display it directly on the console. If a certain use case fails to execute, we usually read the test report first, and then execute the failed use case separately. Go and debug. Because the test framework is set up by myself, you can know the cause by looking at the console when an error is reported. So under what circumstances will logs be used? When your framework is used by many people, or when colleagues who are not familiar with the interface framework use it, they usually don’t know where the error is reported. At this time, they will look at the log report, but under the premise, your log must be complete. That’s fine, otherwise they won’t know what’s wrong

Today’s sharing ends here. If you still don’t understand anything, you can ask in the comment area. If my article is helpful to you, you can like Sanlian to support it

syntaxbug.com © 2021 All Rights Reserved.