1.logging模塊輸出日志
import logging as logger import time import datetime print(time.localtime(),datetime.datetime.now()) print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) print("---------->>>",time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())) logger.basicConfig(level=logger.DEBUG,format='%(asctime)s %(lineno)s -%(levelname)s- -%(filename)s - %(message)s', datefmt="%Y-%m-%d %H:%M:%S") logger.debug("This is debug") logger.info("This is info") logger.warning("This is warning") print("{:.^30}".format("ok"))
2.將日志同時輸出到文件和終端
import logging logger = logging.getLogger(__file__) logger.setLevel(logging.DEBUG) # 建立一個filehandler來把日志記錄在文件里,級別為debug以上 fh = logging.FileHandler("log.log") fh.setLevel(logging.DEBUG) # 建立一個streamhandler來把日志打在CMD窗口上,級別為error以上 ch = logging.StreamHandler() ch.setLevel(logging.ERROR) # 設置日志格式 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(lineno)s %(message)s",datefmt="%Y-%m-%d %H:%M:%S") ch.setFormatter(formatter) fh.setFormatter(formatter) #將相應的handler添加在logger對象中 logger.addHandler(ch) logger.addHandler(fh) # 開始打日志 logger.debug("debug message") logger.info("info message") logger.warn("warn message") logger.error("error message") logger.critical("critical message")