Happy Coder
Happy Coder

Reputation: 4682

Python logger duplicate log messages

I have the following configuration for logger:

def setup_logger(self):

    self.logger = logging.getLogger("root")
    self.logger.setLevel(logging.DEBUG)

    ch = logging.StreamHandler()
    logging.basicConfig(
        format='%(asctime)s - %(message)s',
        datefmt='%d-%b-%y %H:%M:%S'
    )

    self.logger.addHandler(ch)

I call the setup_logger() in the constructor(__init()) and I using the logger like

self.logger.info("Getting data from database")

Now the problem is, that it is showing the log message two times in the terminal when I execute the file. One is with the date and time and the other is without time. It is like the following screenshot

enter image description here

I only need to show the log message with the timestamp and don't need the other one. How can I get rid of the duplicate one? I tried to remove the self.logger.setLevel(logging.DEBUG), but then it is not showing any message. Please help.

Upvotes: 0

Views: 198

Answers (1)

degrees-of-freedom
degrees-of-freedom

Reputation: 873

import logging

logger = logging.getLogger("root")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(message)s', '%d-%b-%y %H:%M:%S')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)

logger.info("Getting data from database")
logger.info("Generating report for month - January")

Upvotes: 1

Related Questions