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?

4 Answers 4

5

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()
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

2

Yes, you can configure it.

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

1 Comment

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.
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")

2 Comments

How would this work for views.py if app.py calls views.py for use with add_url_rule? It would be circular.
You have to use the with app.app_context() to push a flask app context anyway since you are doing your add_url_rule() in a separate module anyway and need the app instance to call that function anyway. If you are using application factory method you should be establishing your url rules in a separate module anyway so you would need that. In which you would be using the current_app import already. And the import of the current_app isn't really a new import, rather imports a Proxy object that points to the current app. You really aren't imported a module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.