首页 > 解决方案 > 如何使用 Python 从 Azure Functions 中的辅助线程重定向日志

问题描述

我正在使用 Azure 函数来运行启动多个线程的 Python 脚本(出于性能原因)。一切都按预期工作,除了只有来自 main() 线程的信息日志出现在 Azure Functions 日志中。我在 main() 中启动的“辅助”线程中使用的所有日志都不会出现在 Azure Functions 日志中。

有没有办法确保来自辅助线程的日志显示在 Azure Functions 日志中?

我使用的模块是“日志”和“线程”。

我正在使用 Python 3.6;我已经尝试降低辅助线程中的日志记录级别,但不幸的是这并没有帮助。各种辅助线程功能位于不同的模块中。

我的函数具有类似于以下伪代码的结构:

def main()->None:
  logging.basicConfig(level=logging.INFO)
  logging.info("Starting the process...")
  thread1 = threading.Thread(target=foo,args=("one arg",))
  thread2 = threading.Thread(target=foo,args=("another arg",))
  thread3 = threading.Thread(target=foo,args=("yet another arg",))
  thread1.start()
  thread2.start()
  thread3.start()
  logging.info("All threads started successfully!")
  return

# in another module

def foo(st:str)->None:
  logging.basicConfig(level=logging.INFO)
  logging.info(f"Starting thread for arg {st}")

当前 Azure 日志输出为:

INFO: Starting the process...
INFO: "All threads started successfully!"

我希望它是这样的:

INFO: Starting the process...
INFO: "All threads started successfully!"
INFO: Starting thread for arg one arg
INFO:Starting thread for arg  another arg
INFO:Starting thread for arg  yet another arg

(当然,辅助线程的顺序可以是任何东西)

标签: pythonmultithreadingazureloggingazure-functions

解决方案


推荐阅读