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 –
With this configuration, no logging will occur by default.
If the logging system gets configured, log messages will start to appear.
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.
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 –
CRITICAL:abc:A Critical Error! DEBUG:abc:A debug message
- Logging in Python
- Python | Add Logging to a Python Script
- Create an Exception Logging Decorator in Python
- Python | Logging Test Output to a File
- Top 8 Python Libraries for Data Visualization
- Best Python libraries for Machine Learning
- Top 10 Python Libraries for Data Science in 2020
- Finding Mean, Median, Mode in Python without libraries
- Argparse VS Docopt VS Click - Comparing Python Command-Line Parsing Libraries
- Unicode Strings Passing to C Libraries
- Passing NULL-Terminated Strings to C Libraries
- Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
- Python - Read blob object in python using wand library
- Reading Python File-Like Objects from C | Python
- Python | Index of Non-Zero elements in Python list
- twitter-text-python (ttp) module - Python
- MySQL-Connector-Python module in Python
- Python | Convert list to Python array
- Python | PRAW - Python Reddit API Wrapper
- Important differences between Python 2.x and Python 3.x with examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.