logging模块打印log的时候主要有一下几个,级别顺序:CRITICAL>ERROR>WARNING>INFO>DEBUG;
1.日志输出到file:
import logging logger = logging.getLogger(__name__) logger.setLevel(level = logging.INFO) handler = logging.FileHandler("log.txt") handler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.info("Start print log") logger.debug("Do something") logger.warning("Something maybe fail.") logger.info("Finish")
打印的log生成在代码目录下:
2018-09-12 15:43:25,516 - __main__ - INFO - Start print log 2018-09-12 15:43:25,516 - __main__ - WARNING - Something maybe fail. 2018-09-12 15:43:25,516 - __main__ - INFO - Finish
如果要同时兼顾到输出到控制台和file:
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)
logger.addHandler(handler)
logger.addHandler(console)
logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")
同样在log文件和控制台输出:
2018-09-12 16:02:52,266 - __main__ - INFO - Start print log 2018-09-12 16:02:52,290 - __main__ - WARNING - Something maybe fail. 2018-09-12 16:02:52,299 - __main__ - INFO - Finish
封装成类
# -*- coding:utf-8 -*- import logging log_name = "auto_updated.log" class Logger: def __init__(self, path,clevel = logging.DEBUG,Flevel = logging.DEBUG): self.logger = logging.getLogger(path) self.logger.setLevel(logging.DEBUG) fmt = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S') #set CMD log sh = logging.StreamHandler() sh.setFormatter(fmt) sh.setLevel(clevel) #set log file fh = logging.FileHandler(path) fh.setFormatter(fmt) fh.setLevel(Flevel) self.logger.addHandler(sh) self.logger.addHandler(fh) def debug(self,message): self.logger.debug(message) def info(self,message): self.logger.info(message) def war(self,message): self.logger.warn(message) def error(self,message): self.logger.error(message) def cri(self,message): self.logger.critical(message) logger = Logger(log_name, logging.DEBUG, logging.DEBUG) logger.cri("this is critical log")