一般情况下,程序的调试过程中,我们会让它输出某些信息,特别是大型程序,通过这些信息,我们了解程序的运行情况。python提供了一个模块logging,它可以将我们需要的信息,全部保存在一个日志文件中。
python的logging模块写日志,采用排队方式,是线程安全、简单的。
一、日志直接打印在屏幕
# # 直接在屏幕上打印日志,默认级别warning:30 import logging # logging.critical("This is an CRITICAL message") # CRITICAL:root:This is an CRITICAL message # logging.error("This is an ERROR message") # ERROR:root:This is an ERROR message # logging.warning("This is an WARNING message") # WARNING:root:This is an WARNING message # logging.info("This is an INFO message") # logging.debug("This is an DEBUG message") # # 修改日志级别后,直接在屏幕上打印 # logging.basicConfig(level=10,format='%(asctime)s %(levelname)s %(message)s') # logging.critical("This is an CRITICAL message") # 2017-05-11 15:22:34,702 CRITICAL This is an CRITICAL message # logging.error("This is an ERROR message") # 2017-05-11 15:22:34,703 ERROR This is an ERROR message # logging.warning("This is an WARNING message") # 2017-05-11 15:22:34,703 WARNING This is an WARNING message # logging.info("This is an INFO message") # 2017-05-11 15:22:34,703 INFO This is an INFO message # logging.debug("This is an DEBUG message") # 2017-05-11 15:22:34,703 DEBUG This is an DEBUG message
二、日志记录到文件
#-----------------------设置--------------------------------- import logging # 生成一个日志对象 logger = logging.getLogger() # 打开日志文件,追加模式a # 若文件不存在,新建 hander_1 = logging.FileHandler('first_logging.txt') hander_2 = logging.FileHandler('second_logging.txt') # 创建格式 # 默认格式为:"%(message)s"。只有信息,没有时间、信息级别等。 # 自定义格式,可添加时间、信息级别等内容。 fmt =logging.Formatter('%(asctime)s %(levelname)s %(message)s') # 给日志文件应用格式 hander_1.setFormatter(fmt) hander_2.setFormatter(fmt) # 为日志文件指定级别,各级别有对应的数值(尽量少用) # 日志级别大小关系:CRITICAL (50)> ERROR(40) > WARNING(30) > INFO(20) > DEBUG(10) > NOTSET(0) # 若不指定,使用默认级别:WARNING(30) hander_1.setLevel(logging.INFO) hander_2.setLevel(logging.ERROR) # 为日志对象指定日志文件,可同时指定多个文件 logger.addHandler(hander_1) logger.addHandler(hander_2) #-----------------------测试------------------ logging.critical("This is an CRITICAL message") logging.error("This is an ERROR message") logging.warning("This is an WARNING message") logging.info("This is an INFO message") logging.debug("This is an DEBUG message")
浙公网安备 33010602011771号