2

This is my code

logger = logging.getLogger("MAIN")
main_handler_logger = logging.FileHandler("./LOGS/MAIN.log", encoding='utf-8')
main_handler_logger.setLevel(logging.INFO)
main_handler_logger.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(message)s'))
logger.addHandler(main_handler_logger)
logger.info("Started!")

why logging creates an empty .log file? whats wrong?

1 Answer 1

2

You are setting the level on your FileHandler - main_handler_logger. If you set the level for logger it will log to the file.

import logging

logger = logging.getLogger("MAIN")
logger.setLevel(logging.INFO)

main_handler_logger = logging.FileHandler("./LOGS/MAIN.log", encoding="utf-8")
main_handler_logger.setFormatter(
    logging.Formatter("%(asctime)s - %(name)s - %(message)s")
)

logger.addHandler(main_handler_logger)
logger.info("Started!")

For easier setup with logging, I would use the basicConfig function.

import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(message)s",
    filename="myapp.log",
    encoding="utf-8",
)
logger = logging.getLogger("MAIN")
logger.info("Started!")
Sign up to request clarification or add additional context in comments.

1 Comment

Also worth mentioning: if the delay kwarg is set to True on the FileHandler it won't create an empty file on instantiation.

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.