使用 python logging 记录 debug 等日志信息
debug 以上信息写入文件
info 以上信息输出在控制台
- import os
- import logging
- VDE_LOGGING_NAME = "vde_logging"
- LOG_FILE_PATH = os.path.join(os.path.dirname(__file__), "vde_regression.log")
- def logger_initialization():
- # 1. logging
- logger = logging.getLogger(VDE_LOGGING_NAME)
- logger.setLevel(logging.DEBUG)
- # 2.handler
- # file handler
- fh = logging.FileHandler(LOG_FILE_PATH, mode="w")
- fh.setLevel(logging.DEBUG)
- # standard control console
- ch = logging.StreamHandler()
- ch.setLevel(logging.INFO)
- # 3.format
- formatter = logging.Formatter("[%(asctime)s %(name)s].%(levelname)s: %(message)s")
- fh.setFormatter(formatter)
- ch.setFormatter(formatter)
- logger.addHandler(fh)
- logger.addHandler(ch)
- def debug_logging_recoder(debug_msg):
- vde_logging = logging.getLogger(VDE_LOGGING_NAME)
- vde_logging.debug(debug_msg)
- def info_logging_recoder(info_msg):
- vde_logging = logging.getLogger(VDE_LOGGING_NAME)
- vde_logging.info(info_msg)
- if __name__ == '__main__':
- logger_initialization()
- debug_logging_recoder("debug")
- info_logging_recoder("info")
References:
http://www.zlovezl.cn/articles/replacing-print-simple-introduction-to-logging/
https://blog.igevin.info/posts/python-log/
来源: http://www.bubuko.com/infodetail-2440072.html