user4184113 user4184113 - 4 months ago 30
Python Question

How can I log outside of main Flask module?

I have a Python Flask application, the entry file configures a logger on the app, like so:

app = Flask(__name__)
handler = logging.StreamHandler(sys.stdout)

I then do a bunch of logging using

app.logger.debug("Log Message")

which works fine. However, I have a few API functions like:

@app.route('/api/my-stuff', methods=['GET'])
def get_my_stuff():
db_manager = get_manager()
query = create_query(request.args)

service = Service(db_manager, query)
app.logger.debug("Req: {}".format(request.url))

What I would like to know is how can I do logging within that
module/python class. Do I have to pass the app to it? That seems like a bad practice, but I don't know how to get a handle to the app.logger from outside of the main Flask file...


Even though this is a possible duplicate I want to write out a tiny bit of python logging knowledge.

DON'T pass loggers around. You can always access any given logger by logging.getLogger(<log name as string>). By default it looks like* flask uses the name you provide to the Flask class.

So if your main module is called 'my_tool', you would want to do logger = logging.getLogger('my_tool')in the Service module.

To add onto that, I like to be explicit about naming my loggers and packages, so I would do Flask('my_tool')** and in other modules, have sub level loggers like. logger = logging.getLogger('') that all use the same root logger (and handlers).

* No experience, based off other answer. ** Again, don't use flask, dk if that is good practice

Edit: Super simple stupid example

Flask main app

import sys
import logging

import flask

from module2 import hi

app = flask.Flask('tester')

handler = logging.StreamHandler(sys.stdout)
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s'))

def index():
    return "hi"

if __name__ == '__main__':


import logging

log = logging.getLogger('tester.sub')

def hi():
    log.warning('warning test')

Outputs: - - [04/Oct/2016 20:08:29] "GET /index HTTP/1.1" 200 -
2016-10-04 20:08:29,098 - tester - DEBUG - TESTING!
2016-10-04 20:08:29,098 - tester.sub - WARNING - warning test