关于python:python-logging日志模板

35次阅读

共计 1045 个字符,预计需要花费 3 分钟才能阅读完成。

import logging, time, os

# 以后门路
BASE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
# 定义日志文件门路
# LOG_PATH = os.path.join(BASE_PATH, "log")
# if not os.path.exists(LOG_PATH):
#     os.mkdir(LOG_PATH)
filename=os.path.basename(__file__).split(".")[0]

class Logger():

    def __init__(self):
        # self.logname = os.path.join(BASE_PATH, "{}.log".format(time.strftime("%Y-%m-%d")))  # 日志的名称
        self.logname = os.path.join(BASE_PATH, "{}.log".format(filename))  # 日志的名称
        self.logger = logging.getLogger("log")
        self.logger.setLevel(logging.DEBUG)

        self.formater = logging.Formatter('[%(asctime)s][%(filename)s %(lineno)d][%(levelname)s]: %(message)s')

        self.filelogger = logging.FileHandler(self.logname, mode='a', encoding="UTF-8")
        self.console = logging.StreamHandler()
        self.console.setLevel(logging.DEBUG)
        self.filelogger.setLevel(logging.DEBUG)
        self.filelogger.setFormatter(self.formater)
        self.console.setFormatter(self.formater)
        self.logger.addHandler(self.filelogger)
        self.logger.addHandler(self.console)


if __name__ == '__main__':
    logger = Logger().logger
    logger.info("--- 测试开始 111---")
    logger.debug("--- 测试完结 222---")

正文完
 0