Python使用日志模块(logging)调试代码

1.日志五个级别

  • DEBUG:函数logging.debug()
  • INFO:函数logging.info()
  • WARNING:函数logging.warning()
  • ERROR:函数logging.error()
  • CRITICAL:函数logging.critical()

2.test_logging.py

import logging
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s - %(levelnames)s - %(message)s')
logging.debug('Start testing')

def factorial(n):
    logging.debug('Start factorial(%s)' % (n))
    total = 1
    for i in range(1,n+1):
        total *= i
        logging.debug('i is' + str(i) + 'total is ' + str(total))
    logging.debug('End factorial(%s)' % (n))
    return total

print(factorial(5))
logging.debug('End testing')

示例运行结果

=============== RESTART: F:\Software\Python3.9\py\test_logging.py ==============
2020-10-22 12:14:08,796 - DEBUG - Start testing
2020-10-22 12:14:08,807 - DEBUG - Start factorial(5)
2020-10-22 12:14:08,819 - DEBUG - i is 1,total is 1
2020-10-22 12:14:08,829 - DEBUG - i is 2,total is 2
2020-10-22 12:14:08,838 - DEBUG - i is 3,total is 6
2020-10-22 12:14:08,848 - DEBUG - i is 4,total is 24
2020-10-22 12:14:08,856 - DEBUG - i is 5,total is 120
2020-10-22 12:14:08,861 - DEBUG - End factorial(5)
120
2020-10-22 12:14:08,907 - DEBUG - End testing

3.禁用日志

可以向logging.disable()函数传入一个日志级别,它就会禁止该级别和更低级别的日志。所以logging.disable(logging.CRITICAL)可以禁用所有级别的日志。

import logging
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s - %(levelnames)s - %(message)s')
logging.disable(logging.CRITICAL)

4.将日志记录到文件

增加参数filename即可,日志将不会在控制台打印。

import logging
logging.basicConfig(filename='log.txt',level=logging.DEBUG,format='%(asctime)s - %(levelnames)s - %(message)s')


「 文章如果对你有帮助,请点个赞哦^^ 」 

3+