In python Flask app, I can declare a custom stream:
from Flask import Response
import logging
from datetime import datetime
from time import sleep
logger = logging.getLogger('my_log_stream')
handler = logging.StreamHandler()
handler.setFormatter = logging.Formatter('[%(asctime)s] %(levelname)s in %(module)s: %(message)s')
logger.addHandler(handler)
I can create some fake logging data:
def fake_logger_data():
for i in range(100):
current_time = datetime.now().strftime('%H:%M:%S') + "\n"
yield current_time.encode()
sleep(1)
And I can expose the log_stream to the front end:
@app.route("/log_stream", methods=["GET"])
def app_log_stream():
return Response(fake_logger_data(), mimetype="text/event-stream")
Which is then displayed simply:
<pre id="log_output"></pre>
<script>
var source = new EventSource("{{ url_for('app_log_stream') }}");
source.onmessage = function (event) {
document.getElementById('log_output').textContent += event.data + '\n'
};
</script>
But I can't see how I can connect the logging to the event-stream. I have seen some similar questions that are regularly reading a log file but is there a way to "stream" the logs to an event generator of sorts?
Looking through the Python docs, I was expecting to be able to set the stream location as a function in place of the fake_logger_data()
above - https://docs.python.org/3/library/logging.handlers.html - but nothing obvious popped up.