0

Below is my current logging configuration.

I would like to know how can I get my log file cleared every 2 days, as I do have my script running on crontab schedule daily during the day.

logger = logging.getLogger('MyLog')
logger.setLevel(logging.INFO)
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)-5.5s - %(message)s', "%Y-%m-%d %H:%M:%S")
file_handler = logging.FileHandler(
    'MyLog.log', 'a', encoding='utf-8')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

Here's an Example which supposed to clear the log file after each 2 min.

import logging
from logging.handlers import TimedRotatingFileHandler

logger = logging.getLogger('MyLog')
logger.setLevel(logging.INFO)
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)-5.5s - %(message)s', "%Y-%m-%d %H:%M:%S")

file_handler = TimedRotatingFileHandler(
    filename='MyLog.log', when='M', interval=2, encoding='utf-8')

file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.info('Hi')

Output after several running is below (log file not cleared):

2021-04-24 23:14:24 - MyLog - INFO  - Hi
2021-04-24 23:15:26 - MyLog - INFO  - Hi
2021-04-24 23:15:33 - MyLog - INFO  - Hi
2021-04-24 23:15:39 - MyLog - INFO  - Hi
2021-04-24 23:15:40 - MyLog - INFO  - Hi
2021-04-24 23:15:57 - MyLog - INFO  - Hi
2021-04-24 23:16:07 - MyLog - INFO  - Hi
2021-04-24 23:16:11 - MyLog - INFO  - Hi
2021-04-24 23:16:16 - MyLog - INFO  - Hi
2021-04-24 23:16:22 - MyLog - INFO  - Hi
2021-04-24 23:16:23 - MyLog - INFO  - Hi
2021-04-24 23:16:34 - MyLog - INFO  - Hi
2021-04-24 23:17:08 - MyLog - INFO  - Hi
5
  • docs.python.org/3/library/… Commented Apr 24, 2021 at 20:33
  • @jonrsharpe Thanks, i came across that before posting my question. but just want to confirm if that's will handle the job ? TimedRotatingFileHandler(filename='MyLog.log', when='D', interval=2, encoding='utf-8') Commented Apr 24, 2021 at 21:10
  • Perhaps you could test it (maybe on a shorter timescale...) and find out? Commented Apr 24, 2021 at 21:10
  • @jonrsharpe i tried that out with 2 minute interval here but the log file didn't cleared. Commented Apr 24, 2021 at 21:18
  • Then I'd suggest you give a minimal reproducible example of that. Commented Apr 24, 2021 at 21:19

1 Answer 1

1
file_handler = TimedRotatingFileHandler(
  filename='MyLog.log', when='D', interval=2, encoding='utf-8', backupCount=1)

You need a backupCount parameter to delete the old log files.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.