In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly shows you the "python automation test through the log 3-minute positioning bug example analysis", the content is easy to understand, well-organized, hope to help you solve your doubts, the following let the editor lead you to study and learn "python automation test through the log 3-minute positioning bug sample analysis" this article.
1. Simple use of the getting started case import logginglogging.basicConfig (level=logging.DEBUG, # set level Set the output format logging.debug ('This is a debug log') logging.info (' This is an info log') logging.warning ('This is a warning log') logging.error (' This is an error log') logging.critical ('This is a critical log') according to the level display format='% (asctime) s-[% (filename) s muri-> line:% (lineno) d] -% (levelname) slug% (message) s') #
Five log levels are set according to different situations, and different levels of logs are output according to different situations.
The level set by the logger will filter out logs below this level.
Import logginglogging.basicConfig (level=logging.WARNING, # set level, display format='% (asctime) s-[% (filename) Smure-> line:% (lineno) d] -% (levelname) slug% (message) s') # set the output format logging.debug ('This is a debug log') logging.info (' This is an info log') logging.warning ('This is a warning log') logging.error (' This is an error log') logging.critical ('This is a critical log')
2020-09-11 17:39:26667-WARNING-This is a warning log
2020-09-11 17:39:26669-ERROR-This is an error log
2020-09-11 17:39:26669-CRITICAL-This is a critical log
Configuration
The basicConfig method supports the configuration of the following keyword parameters.
Formatting rules
The output format of the log can be freely combined in the following format
Common format:% (asctime) s-[% (filename) s-> line:% (lineno) d] -% (levelname) SV% (message) s
Import logginglogging.basicConfig (level=logging.DEBUG, # setting level, according to the level display format='% (asctime) s-[% (filename) Smurt-> line:% (lineno) d] -% (levelname) slug% (message) s') # sets the output format logging.debug ('This is a debug log')
[DEBUG]-2020-09-11 17 36V 50125-4:This is a debug log
Log is written to file
You only need to configure the filename parameter
Import logginglogging.basicConfig (level=logging.WARNING, # setting level Set the output format logging.debug ('This is a debug log') logging.info (' This is an info log') logging.warning ('This is a warning log') logging.error (' This is an error log') logging.critical ('This is a critical log') according to the level display filename='example.log' format='% (asctime) s-[% (filename) s muri-> line:% (lineno) d] -% (levelname) s line:%% (message) s') #
Note that when fielname is configured, the log will not be output to the console.
II. Advanced usage
Simple code can be used directly through logging, and if you want to use it in depth, you need to use logging in an object-oriented way.
Log component
The logging module contains several components.
Step 1 create a logger import logging# the first step is to create a logger to generate the log logger = logging.getLogger ('% slog'% _ _ name__) logger.setLevel (logging.DEBUG) # set the log level
You can create a logger through the getLogger method. Be careful to give the name or return the root logger.
Set the level of the logger through setLevel.
2 create a log processor # create a text processor to write logs to a file file_handler = logging.FileHandler (filename='py34.log',encoding='utf-8') file_handler.setLevel ('WARNING') # set the log level of the processor # create a console processor to output logs to the console console_handler = logging.StreamHandler () console_handler.setLevel (' INFO') # set the log level of the console processor
The log processor sends the log to the specified location.
FileHandler sends logs to files
StreaHandler sends logging output to data streams such as sys.stdout, sys.stderr, or any file class object, the default sys.stdout, the console.
RotatingFileHandler supports rotation based on log file size
TimedRotatingFileHandler supports rotating log files based on time
See the official documentation for more details
(https://docs.python.org/zh-cn/3/library/logging.handlers.html?utm_source=testingpai.com#module-logging.handlers)
3 create the formatter formatter = logging.Formatter (fmt='% (levelname) s% (asctime) s [% (filename) Smuri-> line:% (lineno) d]:% (message) s')
The formatter needs to be set to the processor
File_handler.setFormatter (formatter) console_handler.setFormatter (formatter) 4 create filter
The filter is used to filter the specified log. The specific use is slightly, generally not needed.
See the official documentation for details.
(https://docs.python.org/zh-cn/3/howto/logging-cookbook.html?utm_source=testingpai.com#filters-contextual)
5 add processor to logger logger.addHandler (file_handler) logger.addHandler (console_handler) 6 logging logger.info ('This is an info')
2020-09-11 22 22 44095-[- > line:1]-INFO:This is an info
Logger.warning ('This is a warning')
2020-09-11 22 23 20 337-[- > line:1]-WARNING:This is a warning
Third, the analysis of the encapsulation function of log module
You can customize the logger name.
Ability to customize log file name and path
Ability to customize log file encoding
Ability to customize log format
Use a time rotation processor and be able to configure
Encapsulated into a function
Create the module log_handler.py in the common directory where you create the following functions.
Import loggingfrom logging.handlers import TimedRotatingFileHandlerdef get_logger (name, filename, encoding='utf-8', fmt=None, when='d', interval=1, backup_count=7 Debug=False): "": param name: logger name: param filename: log file name (including path): param encoding: character encoding: param fmt: log format: param when: log rotation time unit: param interval: interval: param backup_count: number of log files: param debug: debug mode: return: "" "logger = logging.getLogger (name) logger.setLevel (logging.DEBUG) # File processors must generally have a higher level than the console if debug: file_level = logging.DEBUG console_level = logging.DEBUG else: file_level = logging.WARNING console_level = logging.INFO if fmt is None: fmt ='% (levelname) s% (asctime) s [% (filename) Smurf-> line:% (lineno) d]:% (message) s 'file_handler = TimedRotatingFileHandler (filename=filename) When=when, interval=interval, backupCount=backup_count, encoding=encoding) file_handler.setLevel (file_level) console_handler = logging.StreamHandler () console_handler.setLevel (console_level) formatter = logging.Formatter (fmt=fmt) file_handler.setFormatter (formatter) console_handler.setFormatter (formatter) logger.addHandler (file_handler) logger.addHandler (console_handler) return loggerif _ _ name__ = ='_ main__': log = get_logger (name='py41' Filename='py41.log', debug=True, when='s') log.info ('I am general information') import time time.sleep (3) log.warning ('I am warning message') IV. Apply to the project and import
The import of the logger generator function cannot be imported into each use case module like the Excel data reader function. Because it returns a logger object, when the logger generation function is called many times and the logger name is the same, multiple log processors will be added to the same logger, resulting in the problem of duplicate logger.
To solve the above problem, create a file called init.py under the common folder, and the code in this file will be executed automatically and only once when the common module is imported.
Write the following code in the init.py file:
From .log _ handler import get_loggerlogger = get_logger ('py41',' py38.log')
Then you can import it in other modules in the project through the following code
From common import logger
This ensures that the get_logger method is executed only once during the execution of the project.
Keep a log
The function of the log is to record the running state of the program and to provide the basis for locating and analyzing errors when there is something wrong with the program.
When and what logs are needed, based on everyone's understanding of the program, as well as experience.
In our project, the process of use case execution is at the core, so our log also revolves around the execution of use cases.
Use logging to record the test data and test results for each use case, the code is as follows:
... @ list_data (* cases) def test_login (self, case): "" login test "" logger.info ('test case [{}] start testing' .format (case ['title'])) # 1. Test data # the case parameter logger.info passed in (the test data of 'test case [{}] is: {}' .format (case ['title'], case)) # 2. Test step res = login_check (case ['username'], case [' password']) logger.info ('test case [{}]): {}' .format (case ['title'], res)) # 3. Assert try: self.assertEqual (res Case ['expect']) except AssertionError ase: logger.error (' test case [{}] assertion failed '.format (case [' title'])) raise e else: logger.info ('test case [{}] assert success' .format (case ['title'])) finally: logger.info (' test case [{}] Test end') these are all the contents of the article "sample Analysis of python Automation Test locating bug through the Log for 3 minutes" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.