How to use Python's RotatingFileHandler

前端 未结 4 1626
一个人的身影
一个人的身影 2020-12-08 06:51

I\'m trying to do a test run of the logging module\'s RotatingFileHandler as follows:

import logging
from logging.handlers import R         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 07:15

    Python provides 5 logging levels out of the box (in increasing order of severity): DEBUG, INFO, WARNING, ERROR and CRITICAL. The default one is WARNING. The docs says, that

    Logging messages which are less severe than lvl will be ignored.

    So if you use .debug with the default settings, you won't see anything in your logs.

    The easiest fix would be to use logger.warning function rather that logger.debug:

    import logging
    from logging.handlers import RotatingFileHandler
    
    logger = logging.getLogger('my_logger')
    handler = RotatingFileHandler('my_log.log', maxBytes=2000, backupCount=10)
    logger.addHandler(handler)
    
    for _ in range(10000):
        logger.warning('Hello, world!')
    

    And if you want to change logger level you can use .setLevel method:

    import logging
    from logging.handlers import RotatingFileHandler
    
    logger = logging.getLogger('my_logger')
    logger.setLevel(logging.DEBUG)
    handler = RotatingFileHandler('my_log.log', maxBytes=2000, backupCount=10)
    logger.addHandler(handler)
    
    for _ in range(10000):
        logger.debug('Hello, world!')
    

提交回复
热议问题