Mojtaba Asgari
Mojtaba Asgari

Reputation: 135

logging.FileHandler in python creates empty files

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?

Upvotes: 2

Views: 969

Answers (1)

Alex
Alex

Reputation: 7045

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!")

Upvotes: 2

Related Questions