How to execute a function when streamlit is stopped?

Hi all,

We are using Elastic APM to monitor our Streamlit application but we have to close the transaction when the Streamlit session is stopped (with CTRL+C or by closing the browser window) in order to send all the logs of that specific session to Elastic. How can we know if the Streamlit session is shutting down so that we can execute this function?