具有控制台日志记录的RotatingFileHandler

时间:2018-11-25 02:15:09

标签: python

我已经编写了一个初始化函数来配置python日志记录模块以记录到文件和控制台。我想使用RotatingFileHandler限制日志文件的大小。下面的代码不会引起任何错误,并且可以执行我想要的所有操作,但它不会旋转日志。我设置了较小的文件大小以测试情况。

我如何配置以使用轮转日志和具有以下不同格式的控制台?

import logging, logging.handlers

LOG_LEVEL = logging.DEBUG
CONSOLE_LEVEL = logging.DEBUG


def init_logger(fullpath, console_level=CONSOLE_LEVEL, log_level=LOG_LEVEL):
    """
    Setup the logger object

    Args:
        fullpath (str): full path to the log file
    """
    logging.basicConfig(level=LOG_LEVEL,
                format='%(asctime)s %(threadName)-10s %(name)-12s % 
                (levelname)-8s %(message)s',
                datefmt='%m-%d-%y %H:%M:%S',
                filename=fullpath,
                filemode='w')

    _logger = logging.getLogger('_root')
    _logger.setLevel(log_level)

    log_handler = logging.handlers.RotatingFileHandler(filename=fullpath, 
        maxBytes=50, backupCount=10)
    log_handler.setLevel(log_level)
    _logger.addHandler(log_handler)

    console = logging.StreamHandler()
    console.setLevel(console_level)
    # set a format which is simpler for console use
    formatter = logging.Formatter('%(name)-12s: %(levelname)-8s % 
       (message)s')
    # tell the handler to use this format
    console.setFormatter(formatter)
    # add the handler to the root logger
    logging.getLogger('').addHandler(console)
    logging.debug("Creating log file")

1 个答案:

答案 0 :(得分:0)

这是您的日志记录的结​​构:

---root <- I mean real root, which you will get from logging.getLogger([""])
---NormalFileHandler <- Configged by logging.basicConfig, this handler won't rotate file.
---StreamHandler
------_root <- Your root logger, although I don't understand why you want this.
------RotatingFileHandler <- This one will rotate file.

然后使用logging.debug("Creating log file"),这与在root记录器debug上调用logging.getLogger().debug(...)相同。因此,此日志传递给了StreamHandlerNormalFileHandler

这就是为什么您看到文件没有旋转的原因。

正确的配置应为:

def init_logger(fullpath, console_level=CONSOLE_LEVEL, log_level=LOG_LEVEL):
    """
    Setup the logger object

    Args:
        fullpath (str): full path to the log file
    """
    logger = logging.getLogger('YourLogger')
    logger.setLevel(log_level)

    log_handler = logging.handlers.RotatingFileHandler(filename=fullpath, 
        maxBytes=50, backupCount=10)
    log_handler.setLevel(log_level)
    formatter = logging.Formatter('%(asctime)s %(threadName)-10s %(name)-12s % 
                (levelname)-8s %(message)s')
    log_handler.setFormatter(formatter)
    logger.addHandler(log_handler)

    console = logging.StreamHandler()
    console.setLevel(console_level)
    formatter = logging.Formatter('%(name)-12s: %(levelname)-8s % 
       (message)s')
    console.setFormatter(formatter)
    logger.addHandler(console)  # Or you can add it to root logger, but it is not recommended, you should use your own logger instead of root logger. Or it will cause some problems.
    logger.debug("Creating log file")

然后,当您要使用记录器时,应使用:

logger = logging.getLogger('YourLogger')
logger.info(...)
logger.debug(...)