当前位置:网站首页>Logging log usage
Logging log usage
2022-06-28 00:16:00 【sl01224318】
background
When it comes to logs , Whether it's developing code or writing UI automated testing , Are inseparable from the log records , It can give us a position in the problem 、 Defects bring great convenience . Usually, the method most used by testers is to use print To print out logs and error messages , But for some large projects , Use print It's not so convenient . because print The printed log has no time , I don't know the location of the log record , In this case , We can use python Self contained logging modular , It can solve the above problems well .
Environmental preparation
Compiler tools :pycharm
programing language :python
The level of logging
stay python Provided log modular , The log levels are divided into 5 level , Respectively :
1、Debug Level is the most detailed log information , A typical application field scenario is problem diagnosis .
2、INFO The level of detail is second only to DEBUG, Usually only key node information is recorded , It's used to confirm that everything is working as we expected .
3、WARNING Information recorded when something unexpected happens ( Such as , Disk free space is low ), But at this time, the application is still running normally
4、ERROR Because of a more serious problem, some functions can't run normally
5、CRITICAL When there is a serious mistake , Information recorded when the application cannot continue running
'''log Use '''
import logging
logging.basicConfig(level=logging.INFO) # Set up logging Log level of
logging.info('infor Level debugging information ')
logging.debug('debug Level debugging information ')
logging.warning('warning Level debugging information ')
logging.error('error Level debugging information ')
logging.critical('critical Level debugging information ')among log The level of logs increases gradually , By default, the log level is WARNING, lower than WARNING Level logs will not be output .
log Log level settings
It said log Log default output WARNING Grade , But I want to output INFO Level, you need to set the log level output , Before starting logging, you can use logging.basicConfig Method to set the log level .
logging.basicConfig(level=logging.INFO) # Set up logging The log level of is INFO
logging.info(' Output info Level debugging information ')
logging.debug(' Output debug Level debugging information ')
logging.warning(' Output warning Level debugging information ')
logging.error(' Output error Level debugging information ') By setting logging Log level is INFO after , The output is as follows :
Logging.basicConfig Function description
If we want to specify log The format of the log output 、 Save the path , It can be used logging.basicConfig Function to implement , The main parameters are as follows :
1、filename: Specify the file name of the target file in the log , When this setting item is specified, the log information will not be output to the console .
2、filemode: Specify the opening mode of the log file , The default is ‘a', It should be noted that , This option should be in filename Only valid when specified
3、format: Specifies the log format string , Specify the field information contained in the log output and their order ,logging The format fields defined by the module are listed below
4、datefmt: Specify Date / Time format , It should be noted that , This option should be in format It contains the time field %(asctime)s Only when effective
5、level: Specify the log level of the logger
6、stream: Specify the log output target stream, Such as sys.stdout,sys.stderr And the Internet stream. It should be noted that ,stream and filename Can't provide at the same time , Otherwise, it will cause ValueError abnormal
7、style:Python3.2 The newly added configuration item , Appoint format The style of the format string , It can be taken as “%,{,$”,, The default is '%'.
8、handlers:Python3.3 The newly added configuration item , If this option is specified , It should be one created multiple handler The iteratable object of , these handler Will be added to root logger. It should be noted that :filename,stream and handlers Only one of these three configuration items can exist , Not at the same time 2 Or 3 individual , Otherwise, it will cause ValueError abnormal .
mport logging
my_format = '%(asctime)s-%(filename)s-%(module)s-%(lineno)d' #log Log format settings , Print current time , The name of the currently executing program , The current line number 、 modular .
logging.basicConfig(
filename = 'my.log', # Log file name
level = logging.INFO, # Set the log level to INFO level
format=my_format
)
logging.info('infor')
logging.debug('debug')
logging.warning('warning')
logging.error('error')
logging.critical('critical')Open... After running the code my,log You can see the recorded log Information .
Logging Format string of the module
For this format , We can use it together , Between each format, you need to use ”-” Connect , Such as :
my_format = '%(asctime)s-%(filename)s-%(module)s-%(lineno)d'
Use format | Description information | Field / The attribute name |
%(asctime)s | Time to print the log | asctime |
%(filename)s | Print the name of the current executing program | fimename |
%(levelname)s | Print log level name | levelname |
%(message)s | Print log information | message |
%(levelno)s | Print log level values | levelno |
%(pathname)s | Print the path of the currently executing program | pathname |
%(funcName)s | Print the current function of the log | funcName |
%(lineno)d | Print the current line number of the log | lineno |
%(thread)d | Print thread id | thread |
%(threadName)s | Print thread name | threadName |
Log processor
What is? log processor , My understanding is to generate records log The process of processing logs , It's like a porter , Do not produce 、 Make products , Only responsible for moving items to the designated location .Python I have a lot of built-in processors , Common are :
1、StreamHandler Standard stream processor , Send the message to the standard output stream 、 Error flow
2、FileHandler File processor , Send message to file
3、RotatingFileHandler File processor , When the file reaches the specified size , Enable new file storage logs .
4、TimedRotatingFileHandler File processor , Logs rotate log files at specific time intervals .
for example :
import logging
from logging import StreamHandler
from logging import FileHandler
logger = logging.getLogger(__name__)
# Set to DEBUG Level
logger.setLevel(logging.DEBUG)
# Standard stream processor , The set level is WARAING
stream_handler = StreamHandler()
stream_handler.setLevel(logging.WARNING)
logger.addHandler(stream_handler)
# File processor , The set level is INFO
file_handler = FileHandler(filename="test.log")
file_handler.setLevel(logging.INFO)
logger.addHandler(file_handler)
logger.debug("this is debug")
logger.info("this is info")
logger.error("this is error")
logger.warning("this is warning")summary
That's all logging The basic usage of log , I believe that mastering the above methods can help us better understand the log output 、 Print and select , In the future UI Automation is not limited to just using print Print , You can also use logging Module to systematically record error messages , Positioning problems is more convenient !
边栏推荐
- MySQL enterprise parameter tuning practice sharing
- SCU|通过深度强化学习进行微型游泳机器人的步态切换和目标导航
- 夏日的晚会
- At the beginning of reading English literature, I would like to ask you how you should read it in the first place?
- 零基础自学SQL课程 | SQL基本函数大全
- 互联网业衍生出来了新的技术,新的模式,新的产业类型
- MATLB|改进的前推回代法求解低压配电网潮流
- CharSequence初探
- Systematic learning + active exploration is the most comfortable way to get started!
- Safe, fuel-efficient and environment-friendly camel AGM start stop battery is full of charm
猜你喜欢

一文剖析C语言函数
![[PCL self study: Segmentation3] PCL based point cloud segmentation: region growth segmentation](/img/9e/f08ce0729c89b0205c0ac47c523ad7.png)
[PCL self study: Segmentation3] PCL based point cloud segmentation: region growth segmentation

认识微信小程序项目的基本组成结构

免费、好用、强大的开源笔记软件综合评测

现代编程语言:Rust (铁锈,一文掌握钢铁是怎样生锈的)

Cornernet understands from simple to profound

Sentinel

零基础自学SQL课程 | CASE函数

Chenyun pytorch learning notes_ Build RESNET with 50 lines of code

An analysis of C language functions
随机推荐
ASP. Net warehouse purchase, sales and inventory ERP management system source code ERP applet source code
How to find Chinese documents corresponding to foreign documents?
智慧风电 | 图扑软件数字孪生风机设备,3D 可视化智能运维
Golang uses Mongo driver operation -- Query (array related)
Transmitting and receiving antenna pattern
Local visualization tool connects to redis of Alibaba cloud CentOS server
认识微信小程序项目的基本组成结构
用两个栈实现队列[两次先进后出便是先进先出]
request对象、response对象、session对象
How to quote Chinese documents when writing a foreign language?
夏日的晚会
Customize MySQL connection pool
表单form 和 表单元素(input、select、textarea等)
Are the registered accounts of the top ten securities companies safe and risky?
安全省油环保 骆驼AGM启停电池魅力十足
Differences and functions between intranet IP and public IP
互联网的发展为产业的变革和转型提供了新的解决方案
炼金术(6): 可迭代的模型和用例
吴恩达《机器学习》课程总结(11)_支持向量机
Instructions for vivado FFT IP