0

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?

  • Does "app.logger.debug" or something like "app.logger.error"work instead? – JustLudo Sep 07 '22 at 06:36
  • nope that didnt work. Looks like the formatter is not working at all? since the time doesnt get appended? – Mayukh Chakravartti Sep 07 '22 at 12:00
  • Maybe you can achieve the same result by using basicConfig, as the top answer in this question does: https://stackoverflow.com/questions/28330317/print-timestamp-for-logging-in-python – JustLudo Sep 08 '22 at 06:35

1 Answers1

0

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')