python logger logging same entry numerous times
You are adding a new FileHandler to the root logger every time you call that function: the call to logger.getLogger()
without a name argument returns the same logger object every time.
You should call generate_logger()
only once and then simply get the same logger object by calling logger.getLogger()
:
generate_logger()
# .... some time later
log = logger.getLogger()
except AttributeError:
log.error('Opps we got an error')
(note that you do not need generate_logger()
to return a value now)
I also faced the same problem and came across this page. Yes, I was also creating multiple handlers. In generate_logger()
, you can check if there's any other handlers and delete them.
def generate_logger():
import logging
LOG_FILENAME = os.path.join(PROJECT_DIR, "mylog.log")
FORMAT = "%(asctime)s : %(message)s"
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Reset the logger.handlers if it already exists.
if logger.handlers:
logger.handlers = []
fh = logging.FileHandler(LOG_FILENAME)
formatter = logging.Formatter(FORMAT)
fh.setFormatter(formatter)
logger.addHandler(fh)
return logger
I think you're probably getting two handlers added to the logger somehow. Perhaps at some point an implicit handler is being added.