简体   繁体   中英

Python logger: limit log file seems not limit my file

So i want to limit my log file.

import logging
import colorlog
from logging.handlers import RotatingFileHandler

def init_logger(dunder_name, testing_mode) -> logging.Logger:
    log_format = '[%(asctime)s]: [%(levelname)s]: %(message)s'

    bold_seq = '\033[1m'
    colorlog_format = (
        f'{bold_seq} '
        '%(log_color)s '
        f'{log_format}'
    )

    logFile = 'app.log'
    colorlog.basicConfig(format=colorlog_format)

    handler = RotatingFileHandler(logFile, mode='a', maxBytes=50, backupCount=0, encoding=None, delay=0)
    logger = logging.getLogger(dunder_name)

    if testing_mode:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    formatter = logging.Formatter(log_format)
    handler.setFormatter(formatter)
    logger.addHandler(handler)


    return logger

And after define maxBytes=50 i cen see that my log file continue to growing ( 4MB at this moment)

What i doing wrong ?

Because backupCount is 0 .

Rollover occurs whenever the current log file is nearly maxBytes in length; but if either of maxBytes or backupCount is zero, rollover never occurs, so you generally want to set backupCount to at least 1, and have a non-zero maxBytes.

https://docs.python.org/3/library/logging.handlers.html#logging.handlers.RotatingFileHandler

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM