Python logging模块
2021-07-02 08:06
import logging
‘‘‘#1、日志打印
#logging.warning("user [wohaoshuai] attempted wrong password more than 3 times")
#logging.critical("server is down")#2、日志记录到文件里
#如果想把日志写到文件里,也很简单
logging.basicConfig(filename="wohaoshuai.log",level=logging.INFO,format="%(asctime)s %(message)s",datefmt="%Y-%m-%d %H:%M:%S")
#其实asctime就是日志生成时间,message就是消息#level级别一共有以下几个:DEBUG(若级别为debug,则不会存到文件中),INFO,WARNING,ERROR,CRITICAL
logging.debug("this message should go to the log file")
logging.info("so should this")
logging.warning("and this,too")
#其中下面这句中的level=loggin.INFO意思是,把日志记录级别设置为INFO
‘‘‘
#3、要把日志既生成到屏幕又记录到文件#create logger 创建一个logging对象
logger = logging.getLogger("TEST-LOG")
logger.setLevel(logging.DEBUG)#相当于设置全局的level为DEBUG,全局的优先级最高
#create console handler and set level to debug 创建一个负责屏幕输出的handler
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)#create file handler and set level to warning #创建一个文件handler
fh = logging.FileHandler("access.log")
fh.setLevel(logging.INFO)#设置为INFO则INFO以下级别全部打印到文件中#create formatter 创建格式
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")#add formatter to ch and fh 把格式对象赋给屏幕和文件
ch.setFormatter(formatter)
fh.setFormatter(formatter)#add ch and fh to logger
logger.addHandler(ch)
logger.addHandler(fh)# "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")
知识点3中屏幕打印为: