This article mainly explains Python What is a logging system in 、 The use of the log system and the application scenario , It is the key content that must be mastered to develop an automated test framework , In addition, there is a portal for a series of articles below , It's still being updated , Interested partners can also go to check , Don't talk much , Let's have a look ~
Series articles :
Series articles 1:【Python automated testing 1】 meet Python The beauty of the
Series articles 2:【Python automated testing 2】Python Installation configuration and PyCharm Basic use
Series articles 3:【Python automated testing 3】 First knowledge of data types and basic syntax
Series articles 4:【Python automated testing 4】 Summary of string knowledge
Series articles 5:【Python automated testing 5】 List and tuple knowledge summary
Series articles 6:【Python automated testing 6】 Dictionary and collective knowledge summary
Series articles 7:【Python automated testing 7】 Data operator knowledge collection
Series articles 8:【Python automated testing 8】 Explanation of process control statement
Series articles 9:【Python automated testing 9】 Function knowledge collection
Series articles 10:【Python automated testing 10】 File basic operation
Series articles 11:【Python automated testing 11】 modular 、 Package and path knowledge collection
Series articles 12:【Python automated testing 12】 Knowledge collection of exception handling mechanism
Series articles 13:【Python automated testing 13】 class 、 object 、 Collection of attribute and method knowledge
Series articles 14:【Python automated testing 14】Python Basic and advanced exercises of automatic test
Series articles 15:【Python automated testing 15】unittest The core concept and function of test framework
Series articles 16:【Python automated testing 16】 Test case data separation
Series articles 17:【Python automated testing 17】openpyxl Secondary packaging and data driven
Series articles 18:【Python automated testing 18】 Configuration file analysis and practical application
Log is also called program running log , The diary is just like the daily diary written by people , A diary will record a person's major events or important events of the day , Can record every bit of life , You can review later , The log is to record the running events of the program , Do sth at sth , What code is running , What procedures have been implemented , When something goes wrong with your code or program , You can quickly find through the log system , So as to locate the abnormal problems and solve them in time .
The logs we usually see are development logs , So why does the test need a learning log 、 To write the log system ? The reason is simple , That is, after the subsequent completion of the testing framework , We also need to use the logging system to determine whether there are problems with the framework we write , That's why we have to learn .
Even if you're not writing a test framework , It is also necessary to master the log system , It can be used in the development of tools 、 framework design , Read the development log and other aspects , It can also be used to debug your own program .
The log consists of three elements : date 、 Grade 、 Information , The date is the corresponding time , Information is the corresponding content , Specific information will also be output according to the level , There are different levels corresponding to different events :
""" Hierarchy : 1、NOSET --0 It's like not writing , Some nonsense that is useless for log analysis , A journal similar to a journal , Some super ordinary things , Eat every day 、 Work, etc 2、debug --1 Commissioning content , Some additional information , Some remarks similar to running the program , It is mostly used for local debugging and printing of test environment , It helps to locate problems in the test environment 3、info --2 Main function information , What actions does the program do at a certain moment , What has been done , For example, I received a request 、 Sent a request and so on 4、warning --3 Warning level : It is mostly used for warning , No impact on operation , If the corresponding processing is not carried out, modify , A program error may be triggered at some time or event in the future 5、error --4 Error level : Represents that problems such as logic or operation errors have occurred during the execution of the program , It belongs to the important problem of code logic defects , In most cases, it is necessary to deal with 6、critical --5 Lethal : An extremely serious and fatal problem , Similar to a system crash , Need first priority and timely processing , Otherwise, it will seriously affect the operation and logical execution of the program """
To use logs, first create a log collector , Then write the corresponding log content in the corresponding code , The specific usage is as follows :
""" Let's start with a code snippet """
def login(username=None, password=None):
if username is None or password is None:
return {
"code": 400, "msg": " The user name or password is empty "}
if username == " Meng Xiaotian " and password == "123456":
return {
"code": 200, "msg": " Login successful "}
return {
"code": 300, "msg": " Wrong user name or password "}
import logging # Log processing module
# Log collector , Equivalent to a pen , The collector parameter is passed to the collector name
logger = logging.getLogger("my_logger")
""" After joining the log """
def login(username=None, password=None):
if username is None or password is None:
logger.error(" Login failed , The user name or password is empty ")
return {
"code": 400, "msg": " The user name or password is empty "}
if username == " Meng Xiaotian " and password == "123456":
logger.info(" Login successful , Normal information version ")
logger.warning(" Login successful , Warning version ")
return {
"code": 200, "msg": " Login successful "}
return {
"code": 300, "msg": " Wrong user name or password "}
login(" Meng Xiaotian ", "123456")
import logging # Log processing module
# Log collector , Equivalent to a pen , The collector parameter is passed to the collector name
logger = logging.getLogger("my_logger")
""" After joining the log """
def login(username=None, password=None):
if username is None or password is None:
logger.error(" Login failed , The user name or password is empty ")
return {
"code": 400, "msg": " The user name or password is empty "}
if username == " Meng Xiaotian " and password == "123456":
logger.info(" Login successful , Normal information version ")
logger.warning(" Login successful , Warning version ")
return {
"code": 200, "msg": " Login successful "}
return {
"code": 300, "msg": " Wrong user name or password "}
login(" Meng Xiaotian ")
From the above code and running results, we can see ,info
Level logs are not printed , and warning
Warning level and error
The error level is output at the terminal , Most of the time , In a formal environment, we don't need to see Debug
Level log information , Just look at warnings and error messages , It is convenient to locate the problem quickly .
In real projects , The terminal is used for code debugging , Therefore, more detailed debugging information is required , And the formal online environment / The production environment requires log storage in the form of files , It is convenient to check the log afterwards and locate the problem , So in the actual project , Often, the level of the terminal log is inconsistent with that of the actual online log , Generally speaking, the terminal is Debug
Level , The formal environment is info
level
The default log has a hierarchical control mechanism , So there will be info
Not printed , and warning
And error
Will print , And it's all about The log collector controls Of , When we set the default level , Then you can print records according to the corresponding level :
import logging # Log processing module
# Log collector , Equivalent to a pen , The collector parameter is passed to the collector name
logger = logging.getLogger("my_logger")
# The date collector can control the level of this log , Only above this level will it be recorded , The default level is warning
logger.setLevel("INFO") # The level needs to be capitalized
""" 1、 Stream processor is also called terminal processor , And a file processor 2、 The midrange processor is in Pycharm The log results displayed in the output print area of , The file processor saves to a txt Log results recorded """
# Terminal processor
# Only above handler The level will finally display
# The final display result Need to compare logger and handler The level of both , Which is higher , Which of the output results shall prevail
handler = logging.StreamHandler()
handler.setLevel("INFO")
logger.addHandler(handler)
""" After joining the log """
def login(username=None, password=None):
if username is None or password is None:
logger.error(" Login failed , The user name or password is empty ")
return {
"code": 400, "msg": " The user name or password is empty "}
if username == " Meng Xiaotian " and password == "123456":
logger.info(" Login successful , Normal information version ")
logger.warning(" Login successful , Warning version ")
return {
"code": 200, "msg": " Login successful "}
return {
"code": 300, "msg": " Wrong user name or password "}
login(" Meng Xiaotian ", "123456")
A collector , It can correspond to multiple processors , We can also output to a file , As shown in the figure below , There are results at the terminal , Will also be in a txt Produce results in the file , The result runs in append mode , Execute multiple times and add multiple times :
Added the code of log format , Let's take a look at the following code and running results :
import logging # Log processing module
# Log collector , Equivalent to a pen , The collector parameter is passed to the collector name
logger = logging.getLogger("my_logger")
# The date collector can control the level of this log , Only above this level will it be recorded , The default level is warning
logger.setLevel("DEBUG") # The level needs to be capitalized
""" 1、 Stream processor is also called terminal processor , And a file processor 2、 The midrange processor is in Pycharm The log results displayed in the output print area of , The file processor saves to a txt Log results recorded """
# Terminal processor
# Only above handler The level will finally display
# The final display result Need to compare logger and handler The level of both , Which is higher , Which of the output results shall prevail
handler = logging.StreamHandler()
handler.setLevel("DEBUG")
logger.addHandler(handler)
# A collector , It can correspond to multiple processors
file_handler = logging.FileHandler("DEBUG.txt", encoding="utf-8")
file_handler.setLevel("INFO")
logger.addHandler(file_handler)
# Log format
fmt = logging.Formatter("%(levelname)s:%(name)s:%(message)s")
# Format the processor
file_handler.setFormatter(fmt)
""" After joining the log """
def login(username=None, password=None):
if username is None or password is None:
logger.error(" Login failed , The user name or password is empty ")
return {
"code": 400, "msg": " The user name or password is empty "}
if username == " Meng Xiaotian " and password == "123456":
logger.info(" Login successful , Normal information version ")
logger.warning(" Login successful , Warning version ")
return {
"code": 200, "msg": " Login successful "}
return {
"code": 300, "msg": " Wrong user name or password "}
login(" Meng Xiaotian ", "123456")
See here , Everyone must know the function of format , The log format can provide us with more detailed printing information , So that we can quickly search 、 location , So as to efficiently analyze , Efficient problem solving , The format of the log can also be replaced by other symbols , It may be more readable .
Specific format setting and log system description , You can refer to Python Official website .
# Log format
fmt = logging.Formatter("%(levelname)s - %(name)s - %(message)s")
# Log format
fmt = logging.Formatter("%(asctime)s - %(levelname)s - %(name)s - %(message)s")
Briefly summarize the process of the log system :
""" 1、 initialization logger The collector 2、 Set the level of the collector 3、 initialization handler processor 4、 Set up handler Grade 5、logger add to handler 6、 initialization format Log format 7、handler add to format 8、logger.info() """
import logging # Log processing module
# 1、 initialization logger The collector
# 2、 Set the level of the collector
logger = logging.getLogger(" The collector ")
logger.setLevel("DEBUG")
# 3、 initialization handler processor
# 4、 Set up handler Grade
# 5、logger add to handler
stream_handler = logging.StreamHandler()
stream_handler.setLevel("DEBUG")
logger.addHandler(stream_handler)
file_handler = logging.FileHandler("file_handler.log", encoding="utf-8")
file_handler.setLevel("INFO")
logger.addHandler(file_handler)
# 6、 initialization format Log format
# 7、handler add to format
format_str = "%(asctime)s - %(levelname)s - %(name)s - %(message)s"
fmt = logging.Formatter(format_str)
# 8、logger.info()
logger.debug(" Debugging information ")
logger.info(" Normal information ")
logger.warning(" Warning message ")
logger.error(" error message ")
logger.critical(" Crash information ")
All right. ~ The above is all the content shared in this article , Have you learned ? I hope I can help you !