python的logging模块详细使用demo

import logging
import os
from logging import handlers
from datetime import datetime

class MyLog():
    def __init__(self, statusBar=None, level=logging.INFO):
        self.statusBar = statusBar
        LOGGING_MSG_FORMAT = '[%(asctime)s] [%(levelname)s] [%(module)s] [%(funcName)s] [%(lineno)d] %(message)s'
        LOGGING_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
        logging.basicConfig(level=logging.DEBUG,format=LOGGING_MSG_FORMAT,datefmt=LOGGING_DATE_FORMAT)
        self.logger = logging.getLogger("日志模块")
        log_path = os.path.join(os.getcwd(), "logs")
        if not os.path.exists(log_path):
            os.makedirs(log_path)
        log_filepath = os.path.join(log_path, "myapp.log")
        logger = handlers.TimedRotatingFileHandler(log_filepath, "midnight", 1)
        logger.setFormatter(logging.Formatter(LOGGING_MSG_FORMAT))
        self.logger.addHandler(logger)
        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        console.setFormatter(logging.Formatter(LOGGING_MSG_FORMAT))
        self.logger.addHandler(console)

   解读1:

logging.basicConfig(level=logging.DEBUG,format=LOGGING_MSG_FORMAT,datefmt=LOGGING_DATE_FORMAT)  #level控制了其他模块的打印level,例如requests和kafka的调试输出信息。

解读2:
logger = handlers.TimedRotatingFileHandler(log_filepath, "midnight", 1)    #定义每天的日志写入同一个文件中
解读3:
self.logger.addHandler(logger)           #添加logger日志句柄
self.logger.addHandler(console)      #添加控制台日志句柄
 
 
 

猜你喜欢

转载自www.cnblogs.com/elijahxb/p/10817061.html