You should use logging
module in your script :
import logging.handlers
LOG_FILE_NAME = '/var/log/my_script.log'
LOGGING_LEVEL = logging.INFO
formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
handler = logging.handlers.RotatingFileHandler(LOG_FILE_NAME, mode='a', maxBytes=5000000, backupCount=5)
handler.setFormatter(formatter)
log = logging.getLogger("my_script")
log.addHandler(handler)
log.setLevel(LOGGING_LEVEL)
In this example, we configure a log file rotation of 5MB with a retention of 5 files. So each time your log file reach 5MB, the script creates a new log file and archive the old one (5 files max).
Here is an example of code to log data in your log file :
def do_something():
# do stuff here
log.info("Something has been done")
Once you've done that, simply run your python script :
python my_script.py
Everything will be logged in the file you want with automatic log rotation.
If you prefer a rotation based on time, please refer to TimedRotatingFileHandler
https://docs.python.org/2/library/logging.handlers.html#timedrotatingfilehandler