preface
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]( https://img-blog.csdnimg.cn/6663f90e87f842479f1a2b629fec871d.png?x -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) logging.error("error") logging.warning("warning") logging.debug("debug") logging.info("info")
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 log.setLevel(level=logging.ERROR) # # Creating a processor is equivalent to instantiating h = logging.StreamHandler() # # 2. Processor set output level to console h.setLevel(level=logging.DEBUG) # # 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 log.addHandler(h) log.error("error") log.warning("warning") log.debug("debug") log.info("info")
The above is the logger. Let's look at the formatter: similar to the logger:
#Formatter #Create logger log = logging.getLogger() log.setLevel(level=logging.DEBUG) # Create processor logging.StreamHandler() # 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 log.addHandler(h) log.addHandler(h1) # Processor add formatter h.setFormatter(f) h1.setFormatter(f1) log.error("error") log.warning("warning") log.debug("debug") log.info("info")
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() self.log.setLevel(level=logging.DEBUG) 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 self.h.setLevel(level=logging.WARNING) #Processor add formatter self.h.setFormatter(self.set_Formatter()[0]) #Logger add processor self.log.addHandler(self.h) def add_FileHandler(self,file_name):#File processor self.h = logging.FileHandler(file_name,mode='a',encoding='utf-8') self.h.setLevel(level=logging.WARNING) self.h.setFormatter(self.set_Formatter()[1]) self.log.addHandler(self.h) # Call both methods at the same time def get_log(self,file_name): self.add_StreamHandler() self.add_FileHandler(file_name) return self.log lg = Log_object() # res = lg.get_log('encapsulated log. Log ') # res.error("error") # res.warning("warning") # res.debug("debug") # res.info("info")