Python interface automation test output log to console and file

Table of contents

1. The role of the log

2. Log level

3. Several important concepts

Four, Logger recorder

Five, Handle processor

Six, Formatter formatter

7. Application of logs in actual test cases

 

1. The role of the log

The general program log comes from the following requirements:
1. Record the audit log of user operations, and sometimes it is even the requirement of the regulatory department.
2. Quickly locate the source of the problem
3. Track the process of program execution.
4. Track data changes
5. Data statistics and performance analysis
6. Collect operating environment data
Generally after the program goes online, once an exception occurs, the first thing to do is to figure out what happened at that time. What operations did the user do at that time, whether the environment was affected, what changes in the data, whether it happened repeatedly, etc., and then further determine which aspect of the problem it is. After it is determined that it is a program problem, it is handed over to the developer to reproduce, research, and propose a solution. At this time, the log provides us with first-hand information.
 

2. Log level

1. DEBUG Level
  indicates fine-grained information events, mainly used to debug applications.

2. The INFO level
  indicates the coarse-grained level, emphasizing the running process of the application, such as entering a certain business branch.

3. WARN level
  indicates a potential error.

4. ERROR level
  indicates that although an error event occurs, it does not affect the continuous operation of the system.

5.FATAL level
  indicates that each serious error event will lead to the exit of the application.

Log4j recommends using only four levels, and the priorities from high to low are ERROR, WARN, INFO, and DEBUG. Logs that are at or above the logger's currently configured level will be printed.

 

The priority is: DEBUG<INFO<WARNING<ERROR<CRITICAL

The default level of the log is warning level and above, and neither debug nor info will be output to the console

3. Several important concepts

Logger recorder: Provides a log interface for use by application code

Handle processor: where to send log records (generated by the logger), that is, where to output

Filter filter: Provides better granular control, it can decide which log records to output, and provides an elegant way to determine whether a log record is sent to the handle

Formatter formatter: specify the specific format of the logging output

Four, Logger recorder

1 Overview

It is a tree-like hierarchical structure. Before using the interfaces debug, info, warning, error, and critical, you must create a Logger instance, that is, create a logger. If there is no explicit creation, a root logger will be created by default and the default will be applied. The log level (warn), the handler Handle (StreamHandle, which prints the log information on the standard output), and the formatter Formatter (the default format is the output format in the first simple utility).

Created method: logger = logging.getLogger(logger_name)

Logger objects are never instantiated directly, but through module-level functions

Logging.getLogger(name) creates a logger instance. When calling the logging.getLogger(name) function, if the value of the name parameter passed in is the same, an application of a logger object instance will always be returned.

2. After creating a Logger instance, you can use the following methods to set the log level and increase the processor Handle

        logger.setLevel(logging.ERROR) = Set the log level to ERROR, that is, only logs with a log level greater than or equal to ERROR will be output (the default level is warning)

        logger.addHandle(handle_name) = Add a handler to the Logger instance

        logger.removeHandle(handle_name) = remove a handler for the Logger instance
 

Five, Handle processor

1 Overview

handle Send log information to the specified location (file, window)

Handle processor type: StreamHandle, FileHandle, NullHandle

2、StreamHandle

Creation method: sh = logging.StreamHandle(stream==None)

Send log output to console

3、FileHandle

Send log records to a disk file, which inherits the output function of StreamHandle

Creation method: fh = logging.FileHandle(filename,mode='a',encoding=None,delay=False)

4、NullHandle

Doesn't do any formatting or output, it's essentially a "no-op" handler for developers to use

Essentially a "do nothing" handle, used by library developers
 

Six, Formatter formatter

1 Overview

Used to set the output format of the log

Creation method: formatter = logging.Formatter(fmt=None, datefmt=None), fmt and datefmt are used to set the log format and time format

Default format: %(asctime)s-%(levelname)s-%(message)s

Default time format: %Y-%m-%d %H:%M:%S

2. Use the Formatter object to set the final rules, structure and content of the log information

 

7. Application of logs in actual test cases

The encapsulation class is convenient for external files to call the log. The example is mainly completed in the console output log and log output to the external .log file

Steps to encapsulate the log class:

create logger

create handle

create formatter

Configure loggers

On the chestnuts:

1. Create an external log file of the class in the project directory: test.log

2. Encapsulate the Logger class:
 

# 日志综合案例的封装
import logging
 
class Logger():
    def __init__(self, LoggerName, FileName, CmdLevel, FileLevel):
        # LoggerName:实例化对象的名字  FileName:外部文件名   CmdLevel:设置控制台中日志输出的级别  FileLevel:设置文件日志输出的级别
        self.logger = logging.getLogger(LoggerName)
        # 设置日志的级别
        self.logger.setLevel(logging.DEBUG)
        # 设置日志的输出格式
        fmt = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')
 
        # 借助handle将日志输出到test.log文件中
        fh = logging.FileHandler(FileName)
        fh.setLevel(FileLevel)
 
        # 借助handle将日志输出到控制台
        ch = logging.StreamHandler()
        ch.setLevel(CmdLevel)
 
        # 配置logger
        fh.setFormatter(fmt)
        ch.setFormatter(fmt)
 
        # 给logger添加handle
        self.logger.addHandler(fh)
        self.logger.addHandler(ch)
 
    def debug(self,message):
        self.logger.debug(message)
 
    def info(self,message):
        self.logger.info(message)
 
    def warn(self,message):
        self.logger.warning(message)
 
    def error(self,message):
        self.logger.error(message)
 
    def critical(self,message):
        self.logger.critical(message)
 
# 如下为测试代码,实际运行中可以注释掉
if __name__ == "__main__":
    logger = Logger("appium","test.log",CmdLevel=logging.DEBUG,FileLevel=logging.INFO)
    logger.debug("debug message!")
    logger.info("info message!")
    logger.warn("warning message!")
    logger.error("error message!")
    logger.critical("critical message!")

3. Call the Logger class:

Create an instantiated object of the Logger class outside the class, and pass in the required parameters

# 其他类中调用Loger类
# 实例化Logger类,并传入参数
logger = Logger("appium", "test.log", CmdLevel=logging.DEBUG, FileLevel=logging.INFO)
 
class Test:
    logger.debug("debug message!")
    logger.info("info message!")
    logger.warn("warning message!")
    logger.error("error message!")
    logger.critical("critical message!")

4. Output result:

控制台:
2020-09-10 10:32:46,230-appium-DEBUG-debug message!
2020-09-10 10:32:46,230-appium-INFO-info message!
2020-09-10 10:32:46,230-appium-WARNING-warning message!
2020-09-10 10:32:46,230-appium-ERROR-error message!
2020-09-10 10:32:46,230-appium-CRITICAL-critical message!
 
外部文件:
20-09-10 10:32:46,230-appium-INFO-info message!
2020-09-10 10:32:46,230-appium-WARNING-warning message!
2020-09-10 10:32:46,230-appium-ERROR-error message!
2020-09-10 10:32:46,230-appium-CRITICAL-critical message

Guess you like

Origin blog.csdn.net/lzz718719/article/details/131603223