How to: Trace a function or script

The best way to use Kolo today is by using the KoloMiddleware in a Django project. But, if you’re not using Django, or want to trace a specific Python function or script, this guide walks through how to do that with kolo.enable and kolo run

with kolo.enable():

You can use kolo.enable as a context manager:

import kolo


def fibonacci(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return fibonacci(n - 1) + fibonacci(n - 2)


if __name__ == "__main__":
    with kolo.enable():
        print(fibonacci(6))

Kolo’s tracing hooks into function calls and returns, not individual line executions. So for example in the code blow, Kolo will only trace the fibonacci call and return in the with block:

def foo():
    with kolo.enable():
        b = 1 + 2
        f = fibonacci(5)
        return b + f

@kolo.enable()

You can also use kolo.enable as a decorator:

import kolo


@kolo.enable
def fibonacci(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return fibonacci(n - 1) + fibonacci(n - 2)

Kolo will now trace the fibonacci function whenever it is called in your program.

Note

kolo.enable can be nested arbitrarily. The outermost call will be used to generate the trace.

If you want to customise Kolo’s behaviour while using kolo.enable, you can pass a config dictionary:

config = {
    "filters": {
        "include_frames": ["include_path", "/more/data/to/include"],
        "ignore_frames": ["ignore_path"],
    },
}

with kolo.enable(config):
    ...


@kolo.enable(config=config)
def example():
    ...

For more information about including and ignoring frames, see config.toml.

kolo run

kolo run allows you to analyse your program from start to finish.

Basic usage

Use kolo run to run your python script:

$ kolo run python example.py

Once your program exits you can see the trace in the Kolo web app at http://localhost:8000/_kolo/ or in the Kolo VSCode extension.

Tests

kolo run can also be used with unittest or pytest to analyse the execution of your tests. For tests, we recommend using the --one-trace-per-test flag so that you get many small traces instead of one giant trace.

Examples:

$ kolo run --one-trace-per-test python manage.py test
$ kolo run --one-trace-per-test pytest
$ kolo run --one-trace-per-test unittest

Limitations

If your program uses subprocesses or threading, kolo run is unable to analyse this code automatically.

Note

To trace Django requests, always use KoloMiddleware instead of kolo run