Search code examples
pythonpython-logging

How to make the log written only to a file in python?


I need the logger requests to be written only to a file and not to pollute the console My code:

logging.basicConfig(level=logging.INFO)

_log_format = f"[%(asctime)s] %(message)s"

file_handler = logging.FileHandler('logs/db.log')
file_handler.setFormatter(logging.Formatter(_log_format))
logger = logging.getLogger('peewee')
logger.addHandler(file_handler)
logger.setLevel(logging.DEBUG)

All requests are written both to the file and to the screen, and I did not understand how to make it so that the output is only to the file, help I tried like this:

logging.basicConfig(
    level=logging.DEBUG,
    format='[%(asctime)s] %(message)s',
    handlers=[
        logging.FileHandler('logs/db.log')
    ]
)

It doesn't work as I need and it also writes all other logs and I only need to write peewee log


Solution

  • Why are you calling logging.basicConfig? The documentation clearly states:

    Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger.

    Just set up your logger without calling basicconfig.

    import logging
    logger = logging.getLogger('peewee')
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.FileHandler('/tmp/foo.log'))
    
    logger.info('Test')
    

    "Test" is written to /tmp/foo.log and not printed.

    Please read the manuals before posting.