logging的基本使用
Posted nevermore29
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了logging的基本使用相关的知识,希望对你有一定的参考价值。
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
以上是关于logging的基本使用的主要内容,如果未能解决你的问题,请参考以下文章