1

I hope to overwrite the previous logging every time I run the application. I figure it out for FileHandler by specifying file mode being 'w'. Where can I specify similar behaviour for StreamHandler? Consider the following code, if running multiple times, 'test.log' will always show a single line of 'test' while the console will show multiple lines of 'test'.

I tried the flush method but it doesn't work.

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

file_handler = logging.FileHandler('test.log', mode = 'w')
logger.addHandler(file_handler)

streamHandler = logging.StreamHandler()
logger.addHandler(streamHandler)

logger.info('test')

I hope the console will show a single line of 'test' even if running multiple times.

J. Lin
  • 139
  • 3
  • 11

2 Answers2

1

I believe that the best you can do is clear the console window on each execution. You can do that using this helpful function (found here):

import os

def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')

def clear_ipython():
    os.system('!cls' if os.name == 'nt' else '!clear')

Just call the clear_screen() routine at the start of your script.

Jonah Bishop
  • 12,279
  • 6
  • 49
  • 74
0

In the end, I found the following answer works. Do a hasHandlers check first and remove any existing handlers to avoid appending handlers every time.

It's weird that logger.handlers.clear() method is not in the documentation.

https://stackoverflow.com/a/44049484/6442398

J. Lin
  • 139
  • 3
  • 11