Flask App Logging not showing the right output

Question:

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?

Answers:

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')
Answered By: Mayukh Chakravartti
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.