7

My flask application uses a module which gets a logger like this:

import logging
logger = logging.getLogger("XYZ")
...
logger.debug("stuff")

Without having to modify anything in the module, can I configure flask such that the module will get flask's app.logger when it makes the getLogger("XYZ") call?

dcr
  • 967
  • 2
  • 9
  • 20

4 Answers4

4

The Flask logger is accessible during a request or CLI command via current_app.

Example usage:

from flask import current_app, Flask
app = Flask('HelloWorldApp')


@app.route('/')
def hello():
    current_app.logger.info('Hello World!')
    return "Hello World!"


if __name__ == '__main__':
    app.run()
smarlowucf
  • 311
  • 3
  • 11
3

This solution worked to me:

import logging

logger = logging.getLogger('werkzeug')
logger.debug('stuff')

The default Flask configuration seems to use the logger name werkzeug. Adding or changing handlers for this logger changes the way Flask logs.

PS.: Python 3.5, Flask 0.12.2

boechat107
  • 1,654
  • 14
  • 24
2

If you want use your Flask apps logging instance that is already established then all you have to do is import the current app and give it a name for that module.

init.py

from flask import Flask

my_app = Flask(__name__)

my_other_module.py where I want to use Flask app logger

from flask import current_app as my_app

class myClass():
   def __init__(self):
       constructor stuff....

   def my_class_method(self):
      my_app.logger.info("log this message")
1

Yes, you can configure it.

By default flask logger's name is your app name, but flask has setting LOGGER_NAME.

Mike
  • 399
  • 3
  • 4
  • `LOGGER_NAME` became outdated with v1.0 (or at least it's not documented anymore). If i'm not mistaken, the name now solely depends on the name of the app. – nichoio Sep 21 '20 at 14:30