Reputation: 133
import logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.FileHandler(filename='logloglog.log'))
logger.critical('A!')
for handler in logger.handlers:
handler.close()
logger.addHandler(logging.FileHandler(filename='logloglog.log'))
logger.critical('B!')
I am trying to understand why the above code logs B!
string in logloglog.log
file twice. It confuses me, since I log both A!
and B!
only one time. Can you help me?
Upvotes: 1
Views: 169
Reputation: 13549
When a new log message arrives the file handler will automatically reopen the file. so
for handler in logger.handlers:
handler.close()
logger.removeHandler(handler) // add this line.
see the ref.
Upvotes: 1
Reputation: 362726
logger.addHandler
was called twice, so there are two file handlers (pointing at the same filename):
>>> logger.handlers
[<FileHandler /home/wglenn/git/modules/logloglog.log (NOTSET)>,
<FileHandler /home/wglenn/git/modules/logloglog.log (NOTSET)>]
By the time logger.critical('B!')
is called, each handler will write out the event once.
It does not matter that you've closed handlers earlier, logging will just re-open the resource when it needs to emit, if necessary.
Upvotes: 1