Save log into a file using streamlit.logger


How can i save a log file during the execution of a streamlit app?

Steps to reproduce

I use the following lines to declare a log using streamlit api

from streamlit.logger import get_logger

logger = get_logger(__name__)'Hello world')

But this log is not stored into a file. How can I do that?

I run the the app using:

streamlit run

I do not want to use:

streamlit run --logger.level=warning 2>'app_log.log'

Because using it, all external tool used in the app write on the same log.

Hi @Cerri, welcome to the forum! I would recommend simply setting up your own logger, using either the built-in python logger How to write to a file, using the logging Python module? - Stack Overflow or some alternative library like loguru Overview — loguru documentation

I @blackary, thanks!
I tried used the classic python logger, but the file is not created. I must use

streamlit run --logger.level=warning 2>'app_log.log'

@Cerri You might try using loguru, which seems to work fine for me. You can click show code to see the code:

1 Like

@blackary Thanks a lot. I will try it!

@blackary I tried, the log works as well. The only thing is that each line is writed on log multiple times! How can I solve it?

Thanks in advance

@blackary How can I programmatically access the environment details (Python version / Streamlit version)?

import platform

import streamlit as st


Hi @Cerri, in general you should expect your streamlit app to be rerun every time you interact with something on your app. If you absolutely need the log to only run at certain times, you might be able to use st.experimental_memo with a TTL. Or, you could set a flag in st.session_state that keeps track of whether a certain logging statement has already been run, and only call the logging function if that flag is False. Something like:

if not st.session_state["have_logged_thing"]:
    st.session_state["have_logged_thing"] = True

Then it should only get logged once per session.