samkeen / ChatWithRSS

This is a demo project showing how to build a simple AI powered "Chat with RSS"
Apache License 2.0
3 stars 0 forks source link

Add a logging console to the UI #3

Open samkeen opened 1 year ago

samkeen commented 1 year ago

I want a debug log console in the UI. best if it is in a side or bottom panel


Streamlit does not have a built-in logging console, but you can mimic one using the st.text or st.text_area function which allows for updating text on the screen.

First, you need to define a class that will be used for logging, this class will redirect the output to the Streamlit interface. Below is an example of how you can do it:

import streamlit as st
import sys

class StreamlitLogger(object):
    """Logger that will log output in Streamlit app"""
    def __init__(self):
        self.log_messages = ''

    def write(self, message):
        if message != '\n':
            self.log_messages += message

    def flush(self):
        st.text(self.log_messages)

    def get(self):
        return self.log_messages

You can then use it in your Streamlit application as follows:

logger = StreamlitLogger()
sys.stdout = logger  # redirect standard output to the logger

print("This message will be logged.")
logger.flush()  # display the log message in the Streamlit app

Remember that you should call logger.flush() each time you want to update the console in your Streamlit app with the latest logs.

Also, you can get back to standard console output at any time using:

sys.stdout = sys.__stdout__  # get back to standard console output

Please keep in mind that such logging mechanism doesn't provide features you may be accustomed to in standard Python logging, such as different logging levels (DEBUG, INFO, WARN, etc.) or logging to files. If you need more sophisticated logging, you should consider implementing your own version of StreamlitLogger based on Python's built-in logging library.