[Python] Python NiceGUI / FastAPI App Insights Integration

Discussão em 'Python' iniciado por Stack, Março 4, 2025.

  1. Stack

    Stack Membro Participativo

    I'm developing a NiceGUI application in python and wanted to add application insights to the app. I have been able to do this as I'm getting requests and telemetry sent no problem. The issue I'm having is that I cant seem to get my custom logging messages to send to app insights.

    I've previously added the configure_azure_monitor and the same code at this link AppInsights Samples and tried it on my "login" page below but it didnt work. Below is my main app start page, where I call config.py which sets up some common things. Login is where the user goes to if there is no authenticated flag set for them. I'm using the opentelemetry.instrumentation.fastapi FastAPIInstrumentor which sends details to app insights for you, which is working fine. I just dont know how to get my custom log messages to send. Any ideas?

    config.py

    import os
    from nicegui import app
    from services.keyvault_service import load_secrets_into_session, in_memory_secrets
    from dotenv import load_dotenv
    from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
    from azure.monitor.opentelemetry import configure_azure_monitor
    from opentelemetry import trace
    from opentelemetry.trace import (get_tracer_provider)
    from logging import getLogger
    from azure.identity import ManagedIdentityCredential

    def config_dev_environment():
    local_environment = os.getenv("LOCALDEV", "False") == "True"
    if local_environment:
    load_dotenv(".env")
    os.environ["HTTP_PROXY"] = "http://localhost:18080"
    os.environ["HTTPS_PROXY"] = "http://localhost:18080"


    def load_app_config():
    config_dev_environment()
    if not in_memory_secrets:
    load_secrets_into_session()

    def configure_app_insights():
    local_environment = os.getenv("LOCALDEV", "False") == "True"
    if local_environment:
    configure_azure_monitor()
    else:
    configure_azure_monitor(credential=ManagedIdentityCredential(),)

    tracer = trace.get_tracer(__name__, tracer_provider=get_tracer_provider())
    logger = getLogger(__name__)
    FastAPIInstrumentor.instrument_app(app)


    app.py

    from nicegui import ui, app
    from config import load_app_config, configure_app_insights
    from pages import open_workspace, create_workspace
    from middleware import AuthenticationChecker
    import logging
    import os

    load_app_config()
    configure_app_insights()

    app.add_middleware(AuthenticationChecker)

    local_environment = os.getenv("LOCALDEV", "False") == "True"

    if __name__ in {"__main__", "__mp_main__"}:
    if local_environment:
    ui.run(port=80,
    favicon="favicon.ico",
    title="My App",
    else:
    ui.run(port=443,
    favicon="favicon.ico",
    title="My App",
    ssl_keyfile="C:/Certificate/private.pem",
    ssl_certfile="C:/Certificate/public.pem")



    login.py

    AUTH_FLOW_STATES = TTLCache(maxsize=256, ttl=60 * 5)
    REQUIREDGROUPNAME = "MYE–Data"

    logger = getLogger(__name__)

    @ui.page("/login")
    def login():

    ad_scope = in_memory_secrets.get("ADScope")
    ad_redirectURL = get_redirect_url()

    msal_app = msal_setup()
    auth_flow = msal_app.initiate_auth_code_flow(ad_scope, ad_redirectURL)

    if auth_flow is None:
    logger.exception("Auth_flow returned from initiate_auth_code_flow is null.")
    raise ValueError("auth_code_flow is None. Ensure it is properly initialized.")

    # Keep track of the auth_flow information as received from B2C
    browser_id = app.storage.browser.get("id")
    AUTH_FLOW_STATES[browser_id] = auth_flow

    logger.info("Auth flow retrieved and redirecting user to B2C SSO login")

    return RedirectResponse(auth_flow["auth_uri"])

    Continue reading...

Compartilhe esta Página