The strongest, automated testing - custom log classes and log encapsulation (actual combat)


foreword

Before customizing logs, you need to know the following information:

Log collector: can be understood as a container for collecting log information;
log level (Level): DEBUG, INFO, WARNING, ERROR, and CRITICAL
Output channel (Handle): console output, StreamHandle
saves log information in a file: FileHandle

Log format (Format):
generally contains the following information: log time - log name - log level name - file name - line number - log information, etc.

Example:

# 设置日志的输出格式
fmt = "%(asctime)s %(name)s %(levelname)s %(filename)s-%(lineno)d:%(message)s"
formatter = logging.Formatter(fmt)

Note:
In the logging module, the default is the root log collector, and the default output level is: WARNING

Operation process of custom logs

Import the logging module: import logging
Create a log collector: logger = logging.getLogger("the name of the log collector")
Set the log level of the log collector: logger.setLevel(logging.INFO) #Set the level of the collector to INFO

Create an output channel for the log collector (according to the content of the first part: the log output channel includes console output and file output): the following uses the console output as an example to introduce, and the file output is similar

Create an output channel for logging: handle1 = logging.StreamHandle()

The level of the log output channel can be set separately: handle1.setLevel(logging.ERROR) This step is optional

Note:
When the log level of the log output channel is not set, the Level set by the log collector is used by default

If you need to set the log level of the log output channel separately, its log level must be higher than the log collector level, otherwise the setting is invalid.

Set the content format of the log output:

# 4、设置日志的输出格式
fmt = "%(asctime)s %(name)s %(levelname)s %(filename)s-%(lineno)d:%(message)s"
ormatter = logging.Formatter(fmt)

Bind the set log format to the created output channel, that is, associate the log format with the output channel

handler1.setFormatter(formatter)

Add the set output channel to the log collector

logger.addHandler(handler1)

Supplement: The operation process of outputting log information to a file is similar, but there is a little difference from the above

handler2 = logging.FileHandler(filename="xxx.log",encoding="utf-8")

Code

import logging

# 1、创建日志收集器
logger = logging.getLogger(name="login_test")

# 2、设置日志收集器的级别:警告级别
logger.setLevel(logging.WARN)

# 3、设置日志的输出渠道
# 3.1 控制台日志输出
handler1 = logging.StreamHandler()
# 3.2 文件日志输出
handler2 = logging.FileHandler(filename="my_log.log",encoding="utf-8")
# 单独设置输出渠道的日志级别
handler1.setLevel(logging.ERROR)    # 可选

# 4、设置日志的输出格式
fmt = "%(asctime)s %(name)s %(levelname)s %(filename)s-%(lineno)d:%(message)s"
formatter = logging.Formatter(fmt)

# 5、关联3和4
handler1.setFormatter(formatter)
handler2.setFormatter(formatter)

# 6、关联1和5
logger.addHandler(handler1)
logger.addHandler(handler2)

# 测试
logger.warning("登录失败警告")
logger.error("登录debug出错")

Encapsulation of custom logs

Since the operation process of the custom log is relatively fixed, we can encapsulate the custom log into a class. When we need to use it, we only need to import this module.

By viewing the source code, we know that the encapsulated class needs to inherit the logging.Logger class, so that it can inherit the debug(), info() and other functions of the parent class;

From the operation process in the second part, different users may set different log names, log levels and log file information when introducing this module, so these parameters allow users to initialize the log object when instantiating it;

When we need to use a custom log class, just introduce this module.

import logging

# 对日志的操作进行封装
class MyLogger(logging.Logger):

    def __init__(self,name,level,file=None):
        super().__init__(name,level)
        # 设置日志的输出渠道
        handler1 = logging.StreamHandler()
        # 设置日志的输出格式
        fmt = "%(asctime)s %(name)s %(levelname)s %(filename)s-%(lineno)d:%(message)s"
        formatter = logging.Formatter(fmt)
        handler1.setFormatter(formatter)
        # 添加日志的输出渠道
        self.addHandler(handler1)

        if file:
            handler2 = logging.FileHandler(filename=file,encoding="utf-8")
            handler2.setFormatter(formatter)
            self.addHandler(handler2)
            pass
        pass
    pass
The following is the most complete software test engineer learning knowledge architecture system diagram in 2023 that I compiled

1. From entry to mastery of Python programming

Please add a picture description

2. Interface automation project actual combat

Please add a picture description

3. Actual Combat of Web Automation Project

Please add a picture description

4. Actual Combat of App Automation Project

Please add a picture description

5. Resume of first-tier manufacturers

Please add a picture description

6. Test and develop DevOps system

Please add a picture description

7. Commonly used automated testing tools

Please add a picture description

Eight, JMeter performance test

Please add a picture description

9. Summary (little surprise at the end)

Struggle is the background of life, and hard work is the step to realize dreams. Raise the sails of your ideals and embark on the journey of pursuit. Even if there are many difficulties, you must persist in moving forward, because only by struggling can you write a brilliant chapter.

Having dreams is the wealth of life, and making efforts is the way to realize dreams. No matter how many setbacks and difficulties we encounter, go forward bravely and never give up. Only struggle can ignite the spark in our hearts, which will eventually lead us to the other side of glory.

Difficulty is the touchstone of life, and struggle is the key to achievement. Challenge yourself, go beyond the limit, and the sweat of hard work will weave a brilliant chapter. Believe in your own ability, go forward bravely, never forget your original intention, and continue to work hard.

Guess you like

Origin blog.csdn.net/shuang_waiwai/article/details/132007318