Wiki

Clone wiki

consoleLog / Home

Console Logger

Hierarchical logs

The console logger provides a nice interface for hierarchical output. Here's a trivial example to get us started.

>>> import consoleLog
>>> def some_function(n):
...     log = consoleLog.default
...     log.start('Counting to %d' % n, nSteps=n)
...     for i in xrange(n):
...         log.log('Item %d' % i)
...     log.finish()
...
>>> some_function(5)
Counting to 5
├─ Item 0
├─ Item 1
├─ Item 2
├─ Item 3
└─ Item 4

This results in quite readable output. The real power is when logging calls are nested. The output then displays the full nesting hierarchy. You could do it like this:

from consoleLog import default as log 

def make_breakfast():
    log.start('Making breakfast')
    fridge = open_fridge()
    milk = get_milk(fridge)
    museli = get_museli()
    food = milk.pour(museli)
    log.finish()
    return food

In this example, we don't know how many steps are involved in making breakfast. We just tell the logger when it starts and when it's finished. If any of the functions we call, such as open_fridge() logs any actions, then they will appear nested under "Making breakfast". If any of them use log.start or log.finish methods, these sub-lists will also be nested appropriately.

Try it out!

Progress bars

Progress bars are a cinch to use with the withProgress() wrapper. Here's an example:

>>> from consoleLog import withProgress
>>> import time
>>> for i in withProgress(range(1000)):
...     time.sleep(0.1)
[-------------------] 100% (9s)

Try this example in your python console and you'll get to watch the animated progress bar work its way down. Basically, it can wrap any iterator with a __len__ method. It can also be passed a number, e.g. withProgress(my_iter, 100), so that it only updates once every 100 iterations. This can be useful for very fast loops where the progress bar itself may be the slowest part.

Demo

consoleLog comes with a built-in demo. You run it by typing:

>>> import consoleLog
>>> consoleLog.demo()

from your python prompt.

Updated