Hi,
I’m new to browser programming so not too sure how logging works in browsers. I know in Java you can enable Java console/logging and log message will be written to these. How do you you enable browser logging and how would you write to that log. I don’t want to send log messages from the client-side over the internet and incur penalties of client to server trip-time, server processing of client-side log messages and storing client-side messages. I believe the number of log messages stored by Anvil are limited.
Any pointers - youtube videos, blogs, articles etc…would be much appreciated.
Thanks
Haider
You might be interested in the logging module of Anvil Extras
Hmmm I think the problem is going to 150 messages per session. I want to keep the 150 for server-side logs and generally have clients logs logged on the client-side…
There’s two things going on here: The logging in-browser and the logging that Anvil does when you print
something. When you do this, Anvil provides a helpful logging mechanism that streams back to the IDE, as we all know and love. These messages are also written back to your app logs (by black magic) so you can review later, and do contribute to the 150 messages max.
If you do want to only print to the browser WITHOUT streaming logs back to Anvil, you can log using the JS console.log
function. This won’t contribute to your message count, but also won’t be visible in the “Running App Console”. To see them you’ll have to review the Console in your developer tools.
Here’s an implementation for how to log (only) to console:
import anvil.js
def log_console(msg):
anvil.js.window.console.log("CONSOLE: " + msg)
Here’s an example app:
4 Likes
Thanks, I’ll have a butchers at that. I’d rather if client side logs are required we can get the user to switch on logging as you do in Java (console/javalog.txt) and zip it and email it over…
Worth noting that the Logger
class in anvil_extras.logging
can take in a custom stream.
By default the stream is sys.stdout
which is where the print
statements go.
But it doesn’t have to be.
Here’s an implementation that allows a user to download the client logs for the session from a custom logger.
These logs also get logged to the browser console.
Since we don’t use sys.stdout.write(text)
(i.e. print
) the logs never get sent to the anvils logs.
import anvil.js
import anvil.media
from anvil.js.window import console
from anvil_extras.logging import INFO, Logger
class ClientStream:
def __init__(self):
self.chunks = []
def write(self, text):
console.log("%c" + text, "color: hotpink;")
self.chunks.append(text)
def flush(self):
pass
def close(self):
pass
def download(self):
media = anvil.js.to_media(self.chunks, "text/plain", "log_data.txt")
anvil.media.download(media)
client_stream = ClientStream()
client_logger = Logger(name="client", level=INFO, format="{datetime}: {msg}", stream=client_stream)
client_logger.download = client_stream.download
clone:
5 Likes