Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

logging - rewrite if size gets too big?

Tags:

python

logging

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?

like image 560
ealeon Avatar asked Sep 12 '16 02:09

ealeon


People also ask

How do you overwrite a log in Python?

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.

What is logging getLogger (__ Name __)?

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.

What is log maximum size?

The maximum log file size can be configured between 1 megabyte (1,024 kilobytes) and 4 terabytes (4,194,240 kilobytes) in kilobyte increments.

What are the Python logging levels?

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.


1 Answers

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)
like image 69
niemmi Avatar answered Oct 23 '22 03:10

niemmi