Azure 函数 Python 工作框架集AsyncLoggingHandler
作为根记录器的处理程序。从这个处理程序到它的目的地,日志似乎是沿着路径被过滤的invocation_id
.
An invocation_id
如果框架本身启动线程,则设置它,就像它所做的那样main
同步功能。另一方面,如果我们自己从main
函数,我们必须设置invocation_id
在启动的线程中使日志到达其目的地。
This azure_functions_worker.dispatcher.get_current_invocation_id
函数检查当前线程是否有正在运行的事件循环。如果没有发现正在运行的循环,它只是检查azure_functions_worker.dispatcher._invocation_id_local
,这是线程本地存储,用于名为的属性v
的价值invocation_id
.
因为我们启动的线程没有正在运行的事件循环,所以我们必须得到invocation_id
来自context
并将其设置为开azure_functions_worker.dispatcher._invocation_id_local.v
在我们启动的每个线程中。
这invocation_id
是由框架提供的context
的参数main
功能。
在 Ubuntu 18.04、azure-functions-core-tools-4 和 Python 3.8 上进行了测试。
import sys
import azure.functions as func
import logging
import threading
# import thread local storage
from azure_functions_worker.dispatcher import (
_invocation_id_local as tls,
)
def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
logging.info("Starting the process...")
thread1 = threading.Thread(
target=foo,
args=(
context,
"one arg",
),
)
thread2 = threading.Thread(
target=foo,
args=(
context,
"another arg",
),
)
thread3 = threading.Thread(
target=foo,
args=(
context,
"yet another arg",
),
)
thread1.start()
thread2.start()
thread3.start()
logging.info("All threads started successfully!")
name = req.params.get("name")
if not name:
try:
req_body = req.get_json()
except ValueError:
pass
else:
name = req_body.get("name")
if name:
return func.HttpResponse(
f"Hello, {name}. This HTTP triggered function executed successfully."
)
else:
return func.HttpResponse(
"This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
status_code=200,
)
# in another module
def foo(context, st: str) -> None:
# invocation_id_local = sys.modules[
# "azure_functions_worker.dispatcher"
# ]._invocation_id_local
# invocation_id_local.v = context.invocation_id
tls.v = context.invocation_id
logging.info(f"Starting thread for arg {st}")
https://github.com/Azure/azure-functions-python-worker/blob/81b84102dc14b7d209ad7e00be68f25c37987c1e/azure_functions_worker/dispatcher.py https://github.com/Azure/azure-functions-python-worker/blob/81b84102dc14b7d209ad7e00be68f25c37987c1e/azure_functions_worker/dispatcher.py