How can I log which page is accessed

Summary

I found that click pages will not send a http://domain/page_name request to the server but works like single page application and change url by js. This makes impossible logging access by nginx.

So how can I find which page is the most popular?

How can I log page access instead of put logging.info("page_name is accessed") at every page script file in pages folder?

I suspect there might be a way to plug into the internal streamlit event system, but I also suspect that adding a logging.info line like you suggest would be far easier.

I found a solution:

create a log_setup.py file contains this:

from streamlit.web.server.websocket_headers import _get_websocket_headers


_logger = logging.getLogger(__name__)
_logger.setLevel(logging.INFO)

super_add_magic = magic.add_magic


def add_magic_with_log(code, script_path):
    headers = _get_websocket_headers()
    ip= headers["X-Forwarded-IP"]
    _logger.info(f"{ip} access {script_path}")
    return super_add_magic(code, script_path)


magic.add_magic = add_magic_with_log

And import it in every page file.

But it still not perfect, I have to import it everywhere because I’m not sure which page will be accessed first.

In fact, I can just import it in the home page and manually access the page once after server start.

Is there an easy way to plug or inject streamlit behavior?

I can’t find it right now, but there is an issue about this.A suggested workaround is using selenium. What is magic, btw?

Magic is this: Magic - Streamlit Docs

The function is called every time before the page content compiled and insert magic code into it.

2 Likes