logger print twice when using one logger

Question:

from logging import getLogger, INFO, StreamHandler, FileHandler, Formatter

log_file = 'test.txt'
logger = getLogger(__name__)
logger.setLevel(INFO)
handler1 = StreamHandler()
handler1.setFormatter(Formatter('%(message)s'))
handler2 = FileHandler(filename = f'{log_file}.log')
handler2.setFormatter(Formatter('%(message)s'))
logger.addHandler(handler1)
logger.addHandler(handler2)


logger.info("HELLO")

HELLO
INFO:__main__: HELLO

I want to print only "HELLO" without the second print INFO:__main__: HELLO

How can I solve it?

( I ran the code in Colab. )

Asked By: alryosha

||

Answers:

Use logger.propagate = False to prevent logs from going up the chain to some ancestral handler, which I assume is what is happening here.

Answered By: Mr. Fegur
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.