0

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.

2
  • which python version ? Commented Jul 12, 2022 at 7:24
  • you can remove logging.basicConfig this line, but then you've to define a formatter aslo, as done by @ilovebees Commented Jul 12, 2022 at 7:29

1 Answer 1

1
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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.