Home > Mobile >  using python logger to only log selected level
using python logger to only log selected level

Time:03-01

I am trying to only log to file issues of WARNING level or higher, yet the logger loggs everything. My code:

logging.basicConfig(format='%(asctime)s %(message)s',
                    datefmt='%m/%d/%Y %I:%M:%S %p',
                    filename='logfile.log',
                    encoding='utf-8', level=logging.WARNING)
  • my logger:
flasklog = logging.getLogger('flasklog')
flasklog.setLevel('WARNING')

-the logging call:

flasklog.warning("FAILED LOGIN: %s from: %s", feedback, ip_address)
  • I can see in the config that the level is set to WARNING, and yet an output looks like this:
03/01/2022 09:30:57 AM  * Restarting with stat
03/01/2022 09:30:57 AM  * Debugger is active!
03/01/2022 09:30:57 AM  * Debugger PIN: 110-508-916
03/01/2022 09:30:58 AM  * Running on http://127.0.0.1:5000/ (Press CTRL C to quit)
03/01/2022 09:31:07 AM FAILED LOGIN: username doesn't exist from: 127.0.0.1
03/01/2022 09:31:07 AM 127.0.0.1 - - [01/Mar/2022 09:31:07] "POST /login HTTP/1.1" 200 -
03/01/2022 09:31:08 AM 127.0.0.1 - - [01/Mar/2022 09:31:08] "[36mGET /static/style.css HTTP/1.1[0m" 304 -
03/01/2022 09:31:11 AM FAILED LOGIN: username doesn't exist from: 127.0.0.1
03/01/2022 09:31:11 AM 127.0.0.1 - - [01/Mar/2022 09:31:11] "POST /login HTTP/1.1" 200 -
03/01/2022 09:31:11 AM 127.0.0.1 - - [01/Mar/2022 09:31:11] "[36mGET /static/style.css HTTP/1.1[0m" 304 -

CodePudding user response:

It is true, that you have configured your logger to have a WARNING level. But Flask has already configured its default logger and you are finding those log messages in your console.

If you want to disable that logging handle, you can remove it like

from flask.logging import default_handler
app.logger.removeHandler(default_handler)

where app is your Flask app object.

If you want to modify the flask logging configurations, you can refer the documentation available here as of today.

CodePudding user response:

OK, turns out this was answered here: Disable console messages in Flask server

and the code that I needed was:

log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
  • Related