如何设置类属性的每个属性和方法成为类的属性和方法?

时间:2019-08-29 05:22:44

标签: python python-3.x class

所以,我有一个像这样的logCreator类

import logging,logging.handlers

class LogCreator:

    _logLevel = {
        "NOTSET": 0,
        "DEBUG": 10,
        "INFO": 20,
        "WARN": 30,
        "WARNING": 30,
        "ERROR": 40,
        "CRITICAL": 50
    }

    def __init__(self,logFile,
                      level='DEBUG',
                      verbose=True,
                      maxBytes=1024*1024,
                      logFormat='%(asctime)s %(levelname)s %(message)s'):

        self.logger = logging.getLogger(logFile)
        self.logger.setLevel(self._logLevel[level])
        logger_formatter = logging.Formatter(logFormat,
                                             datefmt='%Y-%m-%d %H:%M:%S')

        file_handler = logging.handlers.RotatingFileHandler(logFile, maxBytes=maxBytes, backupCount=1, encoding="UTF-8")
        file_handler.setLevel(self._logLevel[level])
        file_handler.setFormatter(logger_formatter)
        self.logger.addHandler(file_handler)

        if verbose:
            console_handler = logging.StreamHandler()
            console_handler.setLevel(self._logLevel[level])
            console_handler.setFormatter(logger_formatter)
            self.logger.addHandler(console_handler)

LogCreator的属性为logger,因此,如果我想进行一些记录,则必须这样做

l = LogCreator('logfile.log')

# some script
l.logger.info('I just did something')

我觉得它看起来有点丑陋和不直观,如果我能写的话会更好

l = LogCreator('logfile.log')

# some script
l.info('I just did something')

因此,类logger的{​​{1}}属性的每个属性和方法都是该类的属性和方法。我在类初始化结束时通过logCreator进行了尝试,但由于return self.logger必须返回__init__(),因此它引发了错误。

1 个答案:

答案 0 :(得分:0)

我认为您可以添加一些方法来做。像这样:

class LogCreator:
    """ your init code"""

    def info(self, message):
        self.logger.info(message)

    def debug(self, message):
        self.logger.debug(message)

然后您可以使用:

logger = LogCreator('./out.log')

logger.info('info')
logger.debug('debug')

或者。您只能添加一种方法来返回记录器:

def get_logger(self):
    return self.logger

然后使用:

logger = LogCreator('./out.log')

log = logger.get_logger()

log.info('info')
log.debug('debug')