Flask多线程环境下logging

原始链接:https://stackoverflow.com/questions/39476889/use-flask-current-app-logger-inside-threading

You use the standard logging module in the standard way: get the logger for the current module and log a message with it.

def background():
    logging.getLogger(__name__).debug('logged from thread')

app.logger is mostly meant for internal Flask logging, or at least logging within an app context. If you're in a thread, you're no longer in the same app context.

You can pass current_app._get_current_object() to the thread and use that instead of current_app. Or you can subclass Thread to do something similar.

def background(app):
    app.logger.debug('logged from thread')

@app.route('/')
def index():
    Thread(target=background, kwargs={'app': current_app._get_current_object()}).start()
    return 'Hello, World!'
class FlaskThread(Thread):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.app = current_app._get_current_object()

    def run(self):
        with self.app.app_context():
            super().run()

def background():
    current_app.logger.debug('logged from thread')

@app.route('/')
def index():
    FlaskThread(target=background).start()
    return 'Hello, World!'

The same works for multiprocessing.

原文地址:https://www.cnblogs.com/binzhou75/p/11935060.html