1

Just started to look up on the logging module and created a dummy program to understand the logger, handler and formatter. Here is the code

# logging_example.py import logging from datetime import datetime import os extension = datetime.now().strftime("%d-%b-%Y_%H_%M_%S_%p") logfile = os.path.join("logs", f"demo_logging_{extension}.txt") logger = logging.getLogger(__name__) ch = logging.StreamHandler() fh = logging.FileHandler(logfile) ch.setLevel(logging.DEBUG) fh.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") ch.setFormatter(formatter) fh.setFormatter(formatter) logger.addHandler(ch) logger.addHandler(fh) logger.info("Hello World") 

When i execute the program the logs directory has the files but content is empty and nothing gets printed on the screen to. I am pretty sure I am missing something basic but am not able to catch it though :( .

I would appreciate any help.

Thank you

1
  • Did the answer work for you as expected? Commented Jan 25, 2021 at 2:23

1 Answer 1

2

You have added log-level to the handlers but not to the logger. Which means, handler would have logged the message had the logger passed it. But since the logger threshold is higher it got dropped.

See this link

Add log-level to the logger also. After adding the handlers:

logger.setLevel(logging.DEBUG) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.