Python: logging in a library even before enabling logging

logging basicConfig

You can add logging code to a library like in this excample:

examples/python/loglib/lib.py

import logging

def f():
    print("before")
    logging.debug("hello")
    print("after")



and it will not bother the person who uses the library without enabling any logging like this code:

examples/python/loglib/use_without.py

import lib

lib.f()

The output will look like this:

$ python examples/python/loglib/use_without.py
before
after

If the user enabled logging, then that logging will be also included.

examples/python/loglib/use_with.py

import logging
import lib

logging.basicConfig(level = logging.DEBUG)

lib.f()


$ python examples/python/loglib/use_with.py
before
DEBUG:root:hello
after

Related Pages

Python

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Python Maven web site.

Gabor Szabo