Textual – Logging to File and to Textual Console

When you are developing a user interface, it can be valuable to have a log of what’s going on. Creating a log in Textual, a text-based user interface, is even easier than creating one for wxPython or Tkinter. Why? Well, because Textual includes a logger that is compatible with Python’s own logging module, so it’s almost plug-and-play to hook it all up!

You’ll learn how to do this in this short tutorial!

Logging to File and the Console

Textual includes a built-in logging-type handler that you can use with Python’s own logging module called TextualHandler. Python has many built-in logging handler objects that you can use to write to stdout, a file, or even to an email address!

You can hook up multiple handlers to a logger object and write to all of them at once, which gives you a lot of flexibility.

To see how this works in Textual, you will create a very simple application that contains only two buttons. Go ahead and open your favorite Python IDE or text editor and create a new file called log_to_file.py. Then enter the following code into it:

# log_to_file.py

import logging

from textual.app import App, ComposeResult
from textual.logging import TextualHandler
from textual.widgets import Button


class LogExample(App):

    def __init__(self) -> None:
        super().__init__()
        self.logger = logging.getLogger(name="log_example")
        self.logger.setLevel(logging.INFO)
        file_handler = logging.FileHandler("tui.log")
        self.logger.addHandler(file_handler)
        formatter = logging.Formatter(("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
        file_handler.setFormatter(formatter)

        textual_handler = TextualHandler()
        self.logger.addHandler(textual_handler)

    def compose(self) -> ComposeResult:
        yield Button("Toggle Dark Mode", classes="dark mode")
        yield Button("Exit", id="exit")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "exit":
            self.logger.info("User exited")
            self.exit()
        elif event.button.has_class("dark", "mode"):
            self.theme = (
                "textual-dark" if self.theme == "textual-light" else "textual-light"
            )

            self.logger.info(f"User toggled app theme to {self.theme}")



if __name__ == "__main__":
    app = LogExample()
    app.run()

As you can see, you have just two buttons for the user to interact with:

  • Toggle Dark Mode – for toggling dark or light mode
  • Exit – for exiting the application

No matter which button the user presses, the application will log out something. By default, Textual logs to stdout, but you cannot see it because your application will be on screen. If you want to see the logs, you will need to use one of the Textual Console applications, which is part of Textual’s devtools. If you do not have the dev tools installed, you can do so by running this command:

pip install textual-dev

Now that you have the dev tools handy, open up a new terminal window or tab and run this command:

textual console

To get Textual to send the log messages to console, you need to run your Textual application in developer mode. You will run it in a different terminal than Textual Console!

Here’s the special command:

textual run --dev log_to_file.py

You will see various events and other logged metadata appear in the Textual Console regardless of whether you specifically log to it. However, now if you do call self.log or you use Python’s print() function, you will see those appear in your log.

You will also see your log messages in your log file (tui.log), though it won’t include all the extra stuff that Textual Console displays. You only get what you log explicitly written into your log file.

Wrapping Up

And there you have it. You now know how to use Textual’s own built-in logging handler in conjunction with Python’s logging module. Remember, you can use Textual’s logging handler in addition to one or more of Python’s logging modules. You can format the output any way you want too!

Learn More About Logging

If you want to learn more about logging in Python, you might find my book, Python Logging, helpful.

Python Logging book cover

Purchase the book today on GumroadLeanpub or Amazon!