The Wayback Machine - https://web.archive.org/web/20240605160457/https://www.geeksforgeeks.org/python-add-logging-to-python-libraries/
Open In App

Python | Add Logging to Python Libraries

Last Updated : 23 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 : 

Python3




# 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. 

Python3




import somelib
abc.func()


Output : 

NO OUTPUT

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

Python3




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


Output :

CRITICAL:somelib:A Critical Error!

How does it work ?

  • Libraries present a special problem for logging, since information about the environment in which they are used isn’t known.
  • As a general rule, never write library code that tries to configure the logging system on its own or which makes assumptions about an already existing logging configuration.
  • Thus, one needs to take great care to provide isolation.
  • The call to getLogger(__name__) creates a logger module that has the same name as the calling module.
  • Since all modules are unique, this creates a dedicated logger that is likely to be separate from other loggers.
  • The log.addHandler(logging.NullHandler()) operation attaches a null handler to the just created logger object. A null handler ignores all logging messages by default.
  • Thus, if the library is used and logging is never configured, no messages or warnings will appear.

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.



Similar Reads

Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Logging in Python
Logging is a means of tracking events that happen when some software runs. Logging is important for software developing, debugging, and running. If you don't have any logging record and your program crashes, there are very few chances that you detect the cause of the problem. And if you detect the cause, it will consume a lot of time. With logging,
7 min read
Python | Logging Test Output to a File
Problem - Writing the results of running unit tests to a file instead of printed to standard output. A very common technique for running unit tests is to include a small code fragment (as shown in the code given below) at the bottom of your testing file. Code #1 : import unittest class MyTest(unittest.TestCase): ... if __name__ == '__main__': unitt
2 min read
Create an Exception Logging Decorator in Python
Prerequisites: Decorators in Python, Logging in Python Logging helps you to keep track of the program/application you run. It stores the outputs/errors/messages/exceptions anything you want to store. Program executions can be debugged with the help of print statements during the runtime of code. But the code is not elegant and not a good practice.
2 min read
Python VLC Instance - Unsetting Logging Callbacks
In this article we will see how we can unset the logging callbacks from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can c
2 min read
How to Install Python-logging module on Linux?
A programmer's backpack should include a logging library. It can aid in the development of a better knowledge of a program's flow and the discovery of scenarios that you may not have considered when designing. Because most third-party Python libraries employ logging, you may combine your log messages with those from those libraries to create a unif
2 min read
Difference between Logging and Print in Python
In Python, print and logging can be used for displaying information, but they serve different purposes. In this article, we will learn what is python logging with some examples and differences between logging and print in Python. Logging in Python Logging in Python is a technique to display useful messages and warnings to users. The logging module
3 min read
HoneyPot for Getting Logging Activities in Django
In the world of web applications, security is a top priority. One ingenious method for enhancing security is by using a technique known as a "HoneyPot" within Django. While you might envision a HoneyPot as a beehive, in web security, it's quite different. A HoneyPot is a clever deception designed to catch unwanted or malicious bots and spammers in
4 min read
Argparse VS Docopt VS Click - Comparing Python Command-Line Parsing Libraries
Before knowing about the Python parsing libraries we must have prior knowledge about Command Line User Interface. A Command Line Interface (CLI) provides a user-friendly interface for the Command-line programs, which is most commonly favored by the developers or the programmers who prefer keyboard programming, instead of using the mouse. By buildin
4 min read
How to install Python libraries without using the pip command?
The most common practice of installing external libraries in your system is by using the Python pip command. However, there is an alternate method of manually installing Python libraries without using the pip command. In this article, we are going to discuss how to manually install a python package. Below is the Step-by-step approach to manually in
1 min read
Article Tags :
Practice Tags :