Azure Application Insights for Streamlitt apps

I have a Streamlit app running as a Docker container on Azure App Service. I’d like to start using Azure App Insights to log requests and errors. This requires adding telemetry code to the app, as described here.

To add temeltry to a Flask app, I would add the following to the top of the main app.py file:

from opencensus.ext.azure.trace_exporter import AzureExporter
from opencensus.ext.flask.flask_middleware import FlaskMiddleware
from opencensus.trace.samplers import ProbabilitySampler

app = Flask(__name__)
middleware = FlaskMiddleware(
    app,
    exporter=AzureExporter(connection_string=APP_INSIGHTS_CONN_STR),
    sampler=ProbabilitySampler(rate=1.0),
)

Does anyone know how to do this for a Streamlit app? I suspect that I need a different way of defining app in the code above.

2 Likes

You figure this out? I haven’t tried but I also suspected the norm might be an issue running every time. Cache using streamlit?

It is an issue for me too. Anyone has made an implementation here?

I do not have a complete solution to this but one option is to use the open census extensions to add tracing for what happens at the BE.

For example you can add open-census-ext-requests to be attached to any back end stuff. Or you can completely just use the open-census telemetry gatherer to attach to certain BE processes.

opencensus-ext-azure Β· PyPI - you can check out the requests extension in addition to it.
Some code snippet for adding the base logging tracing and initialing the requests. Check out the open census ext from Pypi for more inspiration on how to attach it to your specific needs.

from opencensus.ext.azure.trace_exporter import AzureExporter
from opencensus.trace import attributes_helper
from opencensus.trace import config_integration
from opencensus.trace import stack_trace
from opencensus.trace.samplers import ProbabilitySampler
from opencensus.trace.tracer import Tracer

"""
Tornado server logs are named:  'tornado.access', 'tornado.application', 'tornado.general' currently Not used.
"""
for log_name in ('streamlit', 'access', 'application', 'general'):
    logger = logging.getLogger(log_name)
    logger.setLevel(_config.get_logging_level())
    if app_insights_connection := _config.get_app_insights_connection_string():
        logger.addHandler(AzureLogHandler(connection_string=app_insights_connection))

Another code snippet for adding the requests tracer.

config_integration.trace_integrations(['requests'])
            tracer = Tracer(
                exporter=AzureExporter(
                    connection_string=app_insights_connection,
                ),
                sampler=ProbabilitySampler(1.0),
            )
            log_info('Tracing initialized.')
            return tracer