rsalmei / alive-progress

A new kind of Progress Bar, with real-time throughput, ETA, and very cool animations!
MIT License
5.53k stars 206 forks source link

Output clutter when using custom logging handlers #140

Closed dlesbre closed 2 years ago

dlesbre commented 2 years ago

The output is all messed up when using custom logging handlers. Here is a minimal example:

from alive_progress import alive_bar
from time import sleep
import logging

my_logger = logging.getLogger("my_logger")
my_handler = logging.StreamHandler()
my_logger.addHandler(my_handler) # no logger output without this line
my_logger.setLevel(logging.INFO)

with alive_bar(5) as bar:
    for x in range(5):
        sleep(0.1)
        my_logger.info(f"!!!At step {x} / 5")
        bar()

Which gives the following output

|                                        | ▂▄▆ 0/5 [0%] in 0s (0.0/s, eta: -)!!!At step 0 / 5
|████████                                | ▃▅▇ 1/5 [20%] in 0s (5.0/s, eta: 1s)!!!At step 1 / 5
!!!At step 2 / 5
|████████████████████████                | ▅▇▇ 3/5 [60%] in 0s (7.7/s, eta: 1s)!!!At step 3 / 5
|████████████████████████████████        | ▆█▆ 4/5 [80%] in 0s (8.3/s, eta: 0s)!!!At step 4 / 5
|████████████████████████████████████████| 5/5 [100%] in 0.6s (8.75/s)

While the desired output would be:

!!!At step 0/5
!!!At step 1/5
!!!At step 2/5
!!!At step 3/5
!!!At step 4/5
|████████████████████████████████████████| 5/5 [100%] in 0.6s (8.75/s)

The following code works but I can't refactor my code this way because I use librairies that also use logging and setting the global level just clutters my output...

from alive_progress import alive_bar
from time import sleep
import logging

logging.basicConfig(level=logging.INFO)
my_logger = logging.getLogger("my_logger")
# my_handler = logging.StreamHandler()
# my_logger.addHandler(my_handler)
# my_logger.setLevel(logging.INFO)

with alive_bar(5) as bar:
    for x in range(5):
        sleep(0.1)
        my_logger.info(f"!!!At step {x} / 5")
        bar()

I'm not sure if you can auto-detect custom handlers. If not I'm fine with registering them with something like

from alive_progress import add_logger_hook
...
add_logger_hook(my_logger) # like this
add_logger_hook(my_handler) # or this

Specs: python version 3.9.7 alive-progress version 2.3.1 Terminal: konsole 21.08.1 OS: Kubuntu 21.10 x86_64 Kernel: 5.13.0-30-generic Shell: bash 5.1.8 DE: Plasma 5.22.5 WM: KWin

rsalmei commented 2 years ago

Humm, I see @dlesbre. Thanks for the PR! I'll take a look as soon as I can 👍

rsalmei commented 2 years ago

Hey, it's published! 2.4.0 brings your fix, thanks!