• 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.

  • 相关阅读:
    placement new小结
    template template parameter 模板模板参数
    windows下创建和删除软链接
    gcc下载地址
    map的erase函数小结
    typedef函数指针
    宏定义条件编译中使用多条件
    关于c++模板特例化测试
    tolua使用
    c++多态
  • 原文地址:https://www.cnblogs.com/binzhou75/p/11935060.html
Copyright © 2020-2023  润新知