I am using current_app.logger
and when I tried to log inside thread it says "working outside of application context". How do I log a message from a method running in a thread?
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 -
You use the standard
logging
module in the standard way: get the logger for the current module and log a message with it.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 ofcurrent_app
. Or you can subclassThread
to do something similar.The same works for multiprocessing.