Automatic quick start -- python(16) -- log module

Posted by achintha on Tue, 11 Jan 2022 02:44:28 +0100


This is Qing'an. This article mainly talks about the log module. We need to use this module when writing the automatic test framework, so as to facilitate us to quickly locate errors, understand the operation of the software and more smoothly debug the program.
Someone here will say, when can I reach such a high level when debugging the program. Here, Qing'an only tells you: just practice more. Maybe you listen a lot and say practice more. You might as well think about why you say so.
Some people will also say, why use the log module? Just print directly! So what's the difference between them?
1. Logging can set different logging levels
2. You can specify how and where to output the application scenario: when I need to see a large number of places or view in a file, print is not convenient, so Python introduces the logging module to record the information I want.
3. Compared with print, logging better controls where the output is, how to output and control the message level to filter out unwanted information
The log module is divided into levels: critical > error > warning > info > debug
Different functions correspond to different built-in functions. Let's take a look:
! [insert picture description here]( -oss-process=image/watermark,type_ d3F5LXplbmhlaQ,shadow_ 50,text_ Q1NETiBA5riF5a6J5peg5Yir5LqL,size_ 20,color_ FFFFFF,t_ 70,g_ se,x_ sixteen

Detailed explanation of basicConfig(**kwargs) function parameters:

Format: Specifies the output format and content. Format can output many useful information, as shown in the above example:

  • %(levelno)s: print log level value
  • %(levelname)s: print log level name
  • %(pathname)s: print the path of the currently executing program, which is actually sys argv[0]
  • %(filename)s: print the name of the current executing program
  • %(funcName)s: current function for printing logs
  • %(lineno)d: the current line number of the print log
  • %(actime) s: time to print the log
  • %(thread)d: print thread ID
  • %(threadName)s: print thread name
  • %(process)d: print process ID
  • %(message)s: print log information
import logging

logging.basicConfig(format='%(asctime)s  %(name)s  %(levelno)s '
                           '%(levelname)s   %(filename)s '
                           '%(lineno)d   	%(message)s',level=logging.DEBUG)

Four components of logging

Four components of log: logger, processor, filter and formatter

# Create logger
log = logging.getLogger()
# # # 1. The logger sets the output log level. Debug includes the output of logs above the debug level
# # Creating a processor is equivalent to instantiating
h = logging.StreamHandler()
# # 2. Processor set output level to console
# # Save the log in the file. You can specify the path of disk D and C
h = logging.FileHandler('Qing'an.log',mode='a',encoding='utf-8')
# # Logger add processor


The above is the logger. Let's look at the formatter: similar to the logger:

#Create logger
log = logging.getLogger()
# Create processor
# Create a file processor in append mode
h1 = logging.FileHandler('Formatter log.log',mode='a',encoding='utf-8')
# Create formatter
f = logging.Formatter(fmt='[%(asctime)s  %(levelname)s  %(filename)s:>>>%(message)s]')
# Formatter 2
f1 = logging.Formatter(fmt='[%(asctime)s  %(levelname)s  Number of rows%(lineno)d:>>>%(message)s]')
# Logger add processor
# Processor add formatter


Here I put the formatter and logger together. You can see the effect by directly copying and running. It's easier.

logging encapsulation

Log output steps
1,Create logger
    Set log level
2,Create processor
    Console, file
    Set log level
3,Create formatter
    Format you want to print
4,Logger add processor
5,Processor add formatter
6,Output of logger logs
class Log_object():
    def __init__(self):# Constructor initializes the logger
        self.log = logging.getLogger()

    def set_Formatter(self):#Formatter
        self.f1= logging.Formatter(fmt='[%(asctime)s  %(levelname)s  %(filename)s:>>>%(message)s]')
        self.f2 = logging.Formatter(fmt='[%(asctime)s  %(levelname)s  Number of rows:%(lineno)d:>>>%(message)s]')
        return self.f1,self.f2

    def add_StreamHandler(self):#Console processor
        # Create and initialize the processor
        self.h = logging.StreamHandler()
        # Set processor level
        #Processor add formatter
        #Logger add processor

    def add_FileHandler(self,file_name):#File processor
        self.h = logging.FileHandler(file_name,mode='a',encoding='utf-8')
		# Call both methods at the same time
    def get_log(self,file_name):
        return self.log
lg = Log_object()
# res = lg.get_log('encapsulated log. Log ')
# res.error("error")
# res.warning("warning")
# res.debug("debug")

Topics: Python