python 日誌打印模塊,輸出時間、文件名、行號等信息
通過logging模塊來控制日誌的輸出,相比print直接格式化輸出,更加的方便;可以添加更多的日誌信息,比如時間、行號、文件信息統一輸出;可以通過 setLevel 來統一控制日誌的開啓與關閉。
下面是參考代碼:
#!/usr/bin/env python
# -*-coding:UTF-8-*-
import logging
logging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
datefmt='%d-%m-%Y:%H:%M:%S')
logging.getLogger().setLevel(logging.DEBUG)
logger = logging.getLogger()
logger.debug("This is a debug log")
logger.info("This is an info log")
logger.critical("This is critical")
logger.error("An error occurred\n")
輸出結果:
29-02-2020:12:41:17,935 DEBUG [log.py:11] This is a debug log
29-02-2020:12:41:17,935 INFO [log.py:12] This is an info log
29-02-2020:12:41:17,935 CRITICAL [log.py:13] This is critical
29-02-2020:12:41:17,935 ERROR [log.py:14] An error occurred
如果在項目中需要設置多個不同的日誌輸出器,可以參考下面的代碼:
#!/usr/bin/env python
# -*-coding:UTF-8-*-
import logging
# 設置輸出格式
logging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
datefmt='%d-%m-%Y:%H:%M:%S')
# 設置日誌打印級別
logging.getLogger("test").setLevel(logging.DEBUG)
# 設置日誌輸出器的名字,可以在項目中配置多個不同的日誌輸出器
logger = logging.getLogger("test")
logging.getLogger("info").setLevel(logging.INFO)
logger2 = logging.getLogger("info")
logger.debug("This is a debug log")
logger.info("This is an info log")
logger.critical("This is critical")
logger.error("An error occurred\n")
logger2.debug("This is a debug log")
logger2.info("This is an info log")
logger2.critical("This is critical")
logger2.error("An error occurred")
輸出結果:
29-02-2020:12:36:30,272 DEBUG [log.py:17] This is a debug log
29-02-2020:12:36:30,272 INFO [log.py:18] This is an info log
29-02-2020:12:36:30,272 CRITICAL [log.py:19] This is critical
29-02-2020:12:36:30,272 ERROR [log.py:20] An error occurred
29-02-2020:12:36:30,273 INFO [log.py:23] This is an info log
29-02-2020:12:36:30,273 CRITICAL [log.py:24] This is critical
29-02-2020:12:36:30,273 ERROR [log.py:25] An error occurred