question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to log while using a progress bar from rich without breaking formatting?

See original GitHub issue

Hello,

I am trying to figure out the best way to use loguru to log while also using a rich progress bar. In order to avoid formatting issues, it would seem that I need to use the progress bar’s console.print function, since that is how you avoid breaking the progress bar and causing it to redraw.

I have a couple of thoughts on how to do this, but am still a bit lost:

  • Based on rich’s documentation, it seems like maybe I could create a Console object for my app, add that as a sink somehow, and then pass that to the progress bar.
  • There might also be a way to use the regular logging handler that rich provides, and have loguru propegate messages to that, but I’m not sure how/if that can be hooked up to a rich Console object.

Any advice would be much appreciated! Thanks!

Issue Analytics

  • State:open
  • Created 2 years ago
  • Comments:14 (5 by maintainers)

github_iconTop GitHub Comments

2reactions
Delgancommented, May 18, 2021

Hey @taranlu-houzz.

By default the logger send messages using regular sys.stderr.write() method. As you realized, this causes compatibility problems with Rich’s progressive bars. Both solutions you thought of should work.

You can either use Console.print() as a sink instead of sys.stderr. That way, Rich will be in charge of generating a proper output. As you said, it also requires to pass the console object to the Progress constructor.

import time
from loguru import logger
from rich.console import Console
from rich.progress import Progress

console = Console(color_system=None, stderr=None)

def work(i):
    logger.info("Working: {}", i)
    time.sleep(0.05)

def main():
    logger.info("Before")
    with Progress(console=console) as progress:
        for i in progress.track(range(100)):
            work(i)
    logger.info("After")


if __name__ == "__main__":
    logger.remove()  # Remove default 'stderr' handler

    # We need to specify end=''" as log message already ends with \n (thus the lambda function)
    # Also forcing 'colorize=True' otherwise Loguru won't recognize that the sink support colors
    logger.add(lambda m: console.print(m, end=""), colorize=True)

    main()

I guess it should work similarly using RichHandler(). Again, it seems you have to use your own console object.

handler = RichHandler(console=console)  # Note that RichHandler is adding extra info you may need to disable
logger.remove()
logger.add(handler, colorize=True)
1reaction
Delgancommented, Aug 14, 2021

Thanks for the code snippets @taranlu-houzz!

The color codes are added due to colorize=True. As you realized, this works fine when logs are printed to the console but not when the output is redirected to a file.

As a workaround, you can replace colorize=True with colorize=sys.stderr.isatty(). When colorize=None (the default), Loguru automatically checks if the sink supports colors using the isatty() method. Due to the lambda function, you have to do the same thing explicitly.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Progress Display — Rich 12.6.0 documentation
Rich progress display supports multiple tasks, each with a bar and progress information. You can use this to track concurrent tasks where the...
Read more >
Python Progress Bar THROUGH Logging Module
I have a function of which I want to show a progress bar on one line, flushing the buffer each time.
Read more >
How to Add a Progress Bar to Your 'for' Loops in Python
Today we are going to keep it simple and just have a look at how to show a progress bar for your code....
Read more >
General Look & Feel Settings - Qualtrics
Creating an Account & Logging In · Logging In with Your Organization ID ... Rich Content Editor ... Without Text: A progress bar...
Read more >
Changelog - pip documentation v22.3.1
Utilise rich for presenting pip's default download progress bar. (#10462) ... Start using Rich for presenting error messages in a consistent format.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found