zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    linux上安装vsftpd
    springboot集成mybatisplus
    springboot集成swagger2
    ssm+maven多模块项目整合
    追梦强人工智能(一)
    Linux环境kafka安装
    Linux环境安装jdk10
    东芝笔记本Satellite M40-A
    Maven简介
    postgresql PL/pgSQL—存储过程结构和变量声明
  • 原文地址:https://www.cnblogs.com/binzhou75/p/11935060.html
Copyright © 2011-2022 走看看