close

How to use Python’s RotatingFileHandler

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to use Python’s RotatingFileHandler in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to use Python’s RotatingFileHandler?

  1. How to use Python's RotatingFileHandler?

    Python provides 5 logging levels out of the box (in increasing order of severity): DEBUGINFOWARNINGERROR and CRITICAL. The default one is WARNING.

  2. use Python's RotatingFileHandler

    Python provides 5 logging levels out of the box (in increasing order of severity): DEBUGINFOWARNINGERROR and CRITICAL. The default one is WARNING.

Method 1

Python provides 5 logging levels out of the box (in increasing order of severity): DEBUGINFOWARNINGERROR 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 than 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!')

Method 2

Going off of Kurt Peek’s answer you can also put the rotating file handler in the logging.basicConfig directly

import logging
from logging.handlers import RotatingFileHandler
logging.basicConfig(
        handlers=[RotatingFileHandler('./my_log.log', maxBytes=100000, backupCount=10)],
        level=logging.DEBUG,
        format="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s",
        datefmt='%Y-%m-%dT%H:%M:%S')

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read