python logging 库用来在程序中添加日志输出,可以保存日志至文件,设定输出等级等。
导入模块和基础设置:
设置log文件的名称,以及记录的严重等级
import logging
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
几个logging记录的等级。
logging.debug("This is a debug log.")
logging.info("This is a info log.")
logging.warning("This is a warning log.")
logging.error("This is a error log.")
logging.critical("This is a critical log.")
在别的模块调用
# myapp.py
import logging
import mylib
def main():
logging.basicConfig(filename='myapp.log', level=logging.INFO)
logging.info('Started')
mylib.do_something()
logging.info('Finished')
if __name__ == '__main__':
main()
记录变量数据
变量必须转换为字符串模式。例如下面的‘Look’和‘Leap’,输出中用格式%s来表示。
import logging
logging.warning('%s before you %s', 'Look', 'leap!')
显示时间
logging.basicConfig(format='%(asctime)s %(message)s')