[环境]
Win10、Python3.7.3
[说明]
我有一个函数需要提前返回并做一些后台工作。但是,这些作业中的所有日志消息都不会显示在控制台中(还有应用程序见解)
这是示例代码:
import logging
import time
from threading import Thread
import azure.functions as func
def helper(arg1, arg2):
logger = logging.getLogger(__name__)
for ind in range(3):
logger.info(f'{arg1}, {arg2}, {ind}')
time.sleep(1)
def main(req: func.HttpRequest) -> func.HttpResponse:
logger.info('creating threads ...')
tasks = []
arg_list = [(1, 11), (2, 22), (3, 33)]
for (arg1, arg2) in arg_list :
task = Thread(target=helper, args=[arg1, arg2])
# args:list, kwargs:dict
task.start()
tasks.append(task)
logger.info('leaving the function ...')
return func.HttpResponse("received", status_code=200)
[预期结果]
helper()
生成的所有消息都显示在控制台中(以及应用程序见解)
它应该显示如下内容:
1 11 0
2 22 0
3 33 0
leaving the function
3 33 1
1 11 1
2 22 1
3 33 2
2 22 2
1 11 2
[实际结果]
[2021-07-07T05:38:24.638Z] Executed 'Functions.logging_test' (Succeeded, Id=bb0f4035-7c96-4f79-a7d3-0ba5e7971d05, Duration=28ms)
[2021-07-07T05:45:03.861Z] Executing 'Functions.logging_test' (Reason='This function was programmatically called via the host APIs.', Id=61898196-c1ff-42c6-b668-0c48b2f182c0)
[2021-07-07T05:45:03.881Z] creating threads ...
[2021-07-07T05:45:14.168Z] leaving the function ...
[2021-07-07T05:45:14.173Z] Executed 'Functions.logging_test' (Succeeded, Id=61898196-c1ff-42c6-b668-0c48b2f182c0, Duration=10316ms)
The terminal process "C:\WINDOWS\System32\cmd.exe /d /c func host start" terminated with exit code: 1.
这是我的功能设置
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
},
"logLevel": {
"default": "Warning",
"Function":"Debug"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[1.*, 2.0.0)"
}
}
如有任何建议,我们将不胜感激。
我认为你需要在函数上下文中正确设置线程的incall_id,如下所示:
import azure.functions as func
import threading
import logging
app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
@app.route(route="http_trigger")
def http_trigger(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
t1 = threading.Thread(target=thread_function, args=(context, 'Thread1 used.'))
t1.start()
return func.HttpResponse("Ok", status_code=200)
def thread_function(context: func.Context, message: str):
context.thread_local_storage.invocation_id = context.invocation_id
for _ in range(10):
logging.info(message)
在这里找到了这个。