Open In App

Python | Add Logging to Python Libraries

In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below – Code #1 : 




# abc.py
import logging
 
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
 
# Example function (for testing)
def func():
    log.critical('A Critical Error !')
    log.debug('A debug message')

With this configuration, no logging will occur by default. 






import somelib
abc.func()

Output : 

NO OUTPUT

If the logging system gets configured, log messages will start to appear. Code #2: 






import logging
 
logging.basicConfig()
somelib.func()

Output :

CRITICAL:somelib:A Critical Error!

How does it work ?

Logging of individual libraries can be independently configured, regardless of other logging settings as shown in the code given below – Code #3: 

Python3

import logging

logging.basicConfig(level = logging.ERROR)

import abc
print (abc.func())

Change the logging level for ‘abc’ only
logging.getLogger(‘abc’).level = logging.DEBUG
print (abc.func())
 

Output : 

CRITICAL:abc:A Critical Error!
DEBUG:abc:A debug message

The time complexity of the code is constant time O(1) as there are no loops or iterations.

The space complexity of the code is also constant space O(1) as the amount of memory used does not increase with the size of the input.


Article Tags :