通过logging创建自定义的日志;快速开启/关闭日志;
日志级别——critical error warning info debug
举个例子:
logging 模块的格式化字符串使用c风格
import logging
# 把日志保存到test文件里
# 设置日志级别为 DEBUG,即输出所有级别的日志信息(只输出比该值级别高的日志)
# `format=' %(asctime)s - %(levelname)s - %(message)s'`:设置日志输出格式,其中 `%()` 中的内容表示输出的信息
#`asctime` 表示日志记录的时间,`levelname` 表示日志级别,`message` 表示日志信息。
logging.basicConfig(filename='test_code.txt', level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.debug('start')
def factorial(n):
logging.debug('start of function(%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('enf of function(%s%%)' , n)
return total
print(factorial(5))
# 禁用日志,只禁用debug级别以下的
logging.disable(level=logging.DEBUG)
logging.critical('hi')
logging.info('test info')
logging.debug('end of program')