python - 在线程中使用 Flask current_app.logger

标签 python multithreading logging flask

我正在使用 current_app.logger,当我尝试登录线程内部时,它显示“在应用程序上下文之外工作”。如何记录来自线程中运行的方法的消息?

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

@app.route('/')
def index():
    Thread(target=background).start()
    return 'Hello, World!'
Exception in thread Thread-16:
Traceback (most recent call last):
  File "/usr/lib64/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/usr/lib64/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/home/sapam/demo.py", line 57, in background
    current_app.logger.critical('test')
  File "/home/sapam/.virtualenvs/demo/lib/python3.5/site-packages/werkzeug/local.py", line 343, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/home/sapam/.virtualenvs/demo/lib/python3.5/site-packages/werkzeug/local.py", line 302, in _get_current_object
    return self.__local()
  File "/home/sapam/.virtualenvs/demo/lib/python3.5/site-packages/flask/globals.py", line 51, in _find_app
    raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in a way.  To solve
this set up an application context with app.app_context().  See the
documentation for more information.

127.0.0.1 - - [13/Sep/2016 12:28:24] "GET / HTTP/1.1" 200 -

最佳答案

您以标准方式使用标准logging 模块:获取当前模块的记录器并使用它记录一条消息。

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

app.logger 主要用于内部 Flask 日志记录,或者至少在应用上下文中进行日志记录。如果您在一个线程中,您将不再处于相同的应用程序上下文中。

您可以将 current_app._get_current_object() 传递给线程并使用它代替 current_app。或者您可以子类化 Thread 来做类似的事情。

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!'

同样适用于多处理。

关于python - 在线程中使用 Flask current_app.logger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39476889/

相关文章:

ios - 隐藏奇怪的不需要的 Xcode 日志

linux - 检查部署在多个服务器上的同一应用程序的日志文件的最佳方法是什么?

python - 异常处理的范围规则是什么?

java - 识别访问静态代码块的线程?

java - 如何将参数传递给java中已经运行的线程?

java - 使用大量并发的 SwingWorker

logging - Golang 记录器致命

Pythonic 重构方式更长 0​​x104567910 if-condition-assignment (三元 If )

python pandas ... pandas 中 iterrows 的替代方法来获取下一行值(新)

python - 创建本身就是字典的字典值时索引上的嵌套循环