Azure Functions中FastAPI路由日志无法写入Application Insights的问题
Azure Functions中FastAPI路由日志无法写入Application Insights的解决方法
问题现象
部署在Azure Functions上的FastAPI应用,入口文件__init__.py内的logging.info()日志能正常同步到Application Insights,但路由文件(如route1.py)中的同级别日志无法被采集。路由功能正常,但日志完全缺失。
解决方案
方案1:使用Azure Functions Context内置日志器(推荐)
Azure Functions的context对象自带的日志器已预先配置好与Application Insights的对接,只需将其注入FastAPI应用,路由中直接调用即可:
- 修改
__init__.py的main函数,将context日志器存入FastAPI应用状态:
async def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse: # 注入Azure Functions日志器到FastAPI应用 app.state.logger = context.log return await func.AsgiMiddleware(app).handle_async(req, context)
- 在路由文件
route1.py中,通过Request对象获取应用状态中的日志器:
from fastapi import APIRouter, Request router = APIRouter(prefix="/api/route1") @router.get("/test") def test(request: Request): request.app.state.logger.info("resp route test") return "route test"
方案2:手动同步Azure Functions日志处理器
如果不想依赖context传递,可将Azure Functions默认日志的处理器添加到路由模块的日志器中:
- 在
__init__.py开头保存Azure的日志处理器:
import logging import azure.functions as func from fastapi import FastAPI from .routes import route1 # 保存Azure Functions默认日志处理器 azure_log_handlers = logging.getLogger().handlers app = FastAPI() app.include_router(route1.router) @app.get("/api/test") def test(): logging.info("entry test") return "test" async def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse: return await func.AsgiMiddleware(app).handle_async(req, context)
- 在
route1.py中为当前模块日志器添加处理器:
from fastapi import APIRouter import logging from ..__init__ import azure_log_handlers router = APIRouter(prefix="/api/route1") # 配置路由模块日志器 logger = logging.getLogger(__name__) # 添加Azure的日志处理器 for handler in azure_log_handlers: logger.addHandler(handler) logger.setLevel(logging.INFO) @router.get("/test") def test(): logger.info("resp route test") return "route test"
原因说明
Azure Functions启动时会初始化一套专属的日志系统,而FastAPI路由模块在导入时,其模块级别的logging实例并未自动继承Azure的日志处理器配置。通过上述两种方式,要么直接复用已配置好的context日志器,要么将Azure的处理器同步到路由模块的日志器中,即可让路由内的日志正常写入Application Insights。
内容的提问来源于stack exchange,提问作者Dean MacGregor
相关产品推荐
相关产品推荐

