Textual - How to Log to Both the Console and a File
Textual is a wonderful Python package that allows you to create a text-based user interface (TUI) in your terminal. You may have read about Textual several times in this newsletter.
When you are debugging Textual applications, you can log or print to something called the Textual console. You run this console in a separate terminal and then run your Textual application in developer mode.
Buy Creating TUI Applications with Textual and Python
But what if you want a more permanent log? Well, you can do that too. That is the point of this tutorial after all.
Let’s spend some time learning how this all works.
Starting a Textual Console
Your first step is to start the Textual console. Open a new terminal and run the following command:
If you see an error, then you probably don’t have the Textual developer tools installed.
To install the developer tools, you can run this command:
Now, when you run textual console you should see something like the following in your terminal:
You now need to start your Textual application in developer mode.
Starting Textual Applications in dev-mode
When you want to run a Textual application in developer mode, you need to run the application using the textual command with the —dev command.
Here’s an example command: textual run --dev my_textual_app.py
In your code, you can then use Python’s print() function or self.log.info() or self.log.error(), etc to log to the Textual console.
But how do you log to a file too? Well, you can use the Textual Logging handler in combination with Python’s logging module.
Open up a new Python file in your favorite IDE and add the following code to it:
Here you create a Python logging object in your applications’s __init__() method. You add a regular FileHandler to the logging object, but you also add a TextualHandler too. Python’s logging object will happily write to both handlers at the same time!
Learn more in my Python Logging book
In the on_button_pressed() event handler, you can see an example of calling the logging object using the info() method. This will log out to your file as well as to that separate Textual console window.
Try running the console, then launching this application with the textual run --dev my_textual_app.py command you learned earlier.
Wrapping Up
Textual is a great way to create fast cross-platform applications for your users. Being able to log from your Textual application will give you the tools you need to debug your applications, add audit trails to your applications, or simply keep a record of how your application is used.
Give it a try and let me know how it goes!





