Home > Software engineering >  Flask App Logging not showing the right output
Flask App Logging not showing the right output

Time:09-14

I am trying to log messages with a specific format for an INFO and a the default format for a DEBUG. Below is the code to configure the logger and its handler

logger = logging.getLogger("__name__")
logging.basicConfig( level=logging.DEBUG)

debugHandler = logging.StreamHandler(sys.stdout)
debugHandler.setLevel(logging.DEBUG)

infoHandler = logging.StreamHandler(sys.stdout)
infoHandler.setLevel(logging.INFO)
f2 = logging.Formatter("%(levelname)s:%(name)s:%(asctime)s:%(message)s", "%m/%d/%Y %H:%M:%S")
infoHandler.setFormatter(f2)

logger.addHandler(debugHandler)
logger.addHandler(infoHandler)

Below is the code for when i am calling the log

@app.route('/about')
def about():
    app.logger.info('"About Us" page retrieved')
    return render_template('about.html')

However, i am not getting the desired format. It shows as below:

INFO:app:"About Us" page retrieved
INFO:werkzeug:192.168.4.31 - - [06/Sep/2022 23:48:05] "GET /about HTTP/1.1" 200-

I was expecting it to show something like the below:

INFO:app:09/06/2022 23:48:05:"About Us" page retrieved

What am I doing wrong?

CodePudding user response:

So I did get this to work. Below is the code for the logging part

# Logging
logger = logging.getLogger("__name__")

logging.basicConfig(level=logging.DEBUG)

format = logging.Formatter("%(levelname)s:%(module)s:%(asctime)s, %(message)s", "%m/%d/%Y %H:%M:%S")

debugHandler = logging.StreamHandler(sys.stdout)
debugHandler.setLevel(logging.DEBUG)
debugHandler.setFormatter(format)

logger.addHandler(debugHandler)

Next in order to avoid the log appearing twice I turned propagate off. Note you need to add this line after the app is instantiated

app = Flask(__name__)
app.logger.propagate = False
logger.propagate = False

Code for calling the log remained the same

@app.route('/about')
def about():
  logger.info('"About Us" page retrieved')
  return render_template('about.html')
  • Related