-2

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

  • Welcome to Stack Overflow. Please research your questions thoroughly and review [how to ask](https://stackoverflow.com/help/how-to-ask) before creating a new post. Your question has already been answered here: [python logging only to file](https://stackoverflow.com/questions/33711475/python-logging-only-to-file) – SimonUnderwood May 18 '23 at 23:58
  • I'm not a robot to find this information so quickly and read these manuals as a nerd – Arman Craig May 19 '23 at 19:56

1 Answers1

0

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.

coleifer
  • 24,887
  • 6
  • 60
  • 75