I have a daemon and it logs its operations:
LOG_FILE = '%s/%s.log' % (LOG_DIR, machine_name)
logging.basicConfig(filename=LOG_FILE,
level=logging.DEBUG,
format='%(asctime)s,%(msecs)05.1f '
'(%(funcName)s) %(message)s',
datefmt='%H:%M:%S')
After a while, the log size got really big and there was no space left on the device.
So I had to manually remove the logs and it was fine.
What's the best way to keep the log size not to go over certain limit? Can it be done via logging module or do i need to write external script to just remove the logs every once in a while?
The filemode can be changed to write mode, which will overwrite the previous logs and only save the current ones. Since the filemode is set to w , this means that the log file will be opened in write mode each time basicConfig() is run, which will ultimately overwrite the file.
logger = logging.getLogger(__name__) This means that logger names track the package/module hierarchy, and it's intuitively obvious where events are logged just from the logger name. Sounds like good advice.
The maximum log file size can be configured between 1 megabyte (1,024 kilobytes) and 4 terabytes (4,194,240 kilobytes) in kilobyte increments.
There are six log levels in Python; each level is associated with an integer that indicates the log severity: NOTSET=0, DEBUG=10, INFO=20, WARN=30, ERROR=40, and CRITICAL=50.
You could use RotatingFileHandler
to do the log rotation for you. There's an example in Logging Cookbook at Python docs:
import logging
import logging.handlers
LOG_FILENAME = 'logging_rotatingfile_example.out'
# Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(
LOG_FILENAME, maxBytes=20, backupCount=5)
my_logger.addHandler(handler)
# Log some messages
for i in range(20):
my_logger.debug('i = %d' % i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With