Ask Your Question
2

What is the way to restrict the size of log files in Python?

asked 2023-07-05 01:13:51 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-05 01:28:02 +0000

huitzilopochtli gravatar image

One way to restrict the size of log files in Python is to use the RotatingFileHandler class from the logging module. This class allows you to specify a maximum size for each log file and automatically rotates to a new file once that size is reached.

Here's an example:

import logging
from logging.handlers import RotatingFileHandler

logger = logging.getLogger(__name__)
handler = RotatingFileHandler('logfile.log', maxBytes=1024, backupCount=3)
logger.addHandler(handler)

In this example, the RotatingFileHandler is created with a maximum size of 1024 bytes (1 KB) and a backup count of 3. Once the log file reaches this size, a new file will be created with a new number at the end (i.e. logfile.log.1, logfile.log.2, etc.) and the old log file will be rotated out.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-05 01:13:51 +0000

Seen: 8 times

Last updated: Jul 05 '23