Interfacing with Typer and Rich
Closed this issue · 4 comments
Hi and once again thanks for a great logger package!
I have currently implemented a CLI package with Typer which recently introduced compatibility with Rich.
This provides some really pretty stack traces in the case of errors.
Below a MWE:
import typer
from logger_tt import logger, setup_logging
with_logging = False
def main(name: str):
if with_logging:
setup_logging()
print(f"Hello {name}")
print("Hello" + 3)
if __name__ == "__main__":
typer.run(main)
and run it with python typer_test.py ExampleName
. This produces the following result in my terminal:
Compare this to the result when using logger_tt
(i.e. setting with_logging = True
above):
How does one make Typer and logger_tt
to play together nicely?
I completely understand if you feel that this isn't a issue with logger_tt
but rather Typer, however, maybe I am just overlooking a simple setting that'll make it work.
Can you clarify more on "play together nicely"?
You want to make the traceback
output to shown as a window
with colored text
in the terminal as rich
's output ?
If so, the easiest way is to pass the traceback to rich.traceback.Traceback
, then print it with rich.console.Console.print
.
You can get the logic from typer/main.py
.
For the traceback passing and printing, you can modify the handle_exception function
Have a good day,
Hi @Dragon2fly and thanks for your quick response!
Yeah, I have the following 2 issues:
- How to remove (most of) the irrelevant traceback from Typer, such that only the last few lines, the actual error, are included in the logs (and on screen)
- How to format the errors on screen in a nice way, if not using Rich, then similar to Rich.
I'll tak a look at your suggestions in the meanwhile. Thanks a lot!
Not familiar with typer, but I'm using logger_tt with rich.
You just need to remove the default StreamHandler and add a rich.logging.RichHandler either by editing the config file or by adding a few lines of startup codes, and rich will take care of all the color rendering.
Hey @ZeroRin and thanks a lot for your suggestion - it worked!
Now everything plays nicely together and also looks very slick. Thanks a lot!