Capture traceback in log file #5933
-
Is there a way I can set up the textual logger to either log a traceback to a log file or let my own sys.excepthook handle uncaught exceptions? I would like to end up with this information in a file: |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Thank you for your issue. Give us a little time to review it. PS. You might want to check the FAQ if you haven't done so already. This project is developed and maintained by Will McGugan. Consider sponsoring Will's work on this project (and others). This is an automated reply, generated by FAQtory |
Beta Was this translation helpful? Give feedback.
-
Yes this is possible, not only that but there's an easy way to do it built right into Rich. Its actually not super well documented, I recall when I figured this out I had to dig through some stuff quite manually. But now I can save you from having to go through the same pain. Here's a working example. # Python standard lib
from datetime import datetime
# Textual and Rich
from textual.app import App
from textual.widgets import Static, Button
from textual.containers import Container
from rich.console import Console
from rich.traceback import Traceback
class TextualApp(App[None]):
CSS = """
Screen { align: center middle; }
#my_static { border: solid blue; width: auto;}
"""
def compose(self):
with Container(id="my_container"):
yield Static("Hello, Textual!", id="my_static")
yield Button("Press me to cause a bug", classes="some-tcss-class")
def on_button_pressed(self):
self.query_one("#non_existent_widget") # This will raise an error
def _handle_exception(self, error: Exception) -> None:
self.record_log_files(error)
super()._handle_exception(error)
def record_log_files(self, e: Exception):
with open("error.txt", "w") as log_txt_file:
console = Console(file=log_txt_file, record=True, width=100)
console.print(f"Error Report, recorded at: {datetime.now()}\n")
traceback = Traceback.from_exception(
type(e),
e,
e.__traceback__,
show_locals=True
)
console.print(traceback)
console.save_html("error.html")
TextualApp().run() This will drop an error.txt and error.html file in whatever folder you just ran the script. |
Beta Was this translation helpful? Give feedback.
Yes this is possible, not only that but there's an easy way to do it built right into Rich. Its actually not super well documented, I recall when I figured this out I had to dig through some stuff quite manually. But now I can save you from having to go through the same pain. Here's a working example.