- Trending Categories
- Data Structure
- Operating System
- MS Excel
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to disable logging from imported modules in Python?
Applications can use the logging module to configure various log handlers and to route log messages to these handlers. This enables a very flexible design that can handle a wide range of use cases.
A caller must first request a named logger in order to produce a log message. The program can set up various rules for various loggers using the name.
The program can then utilise this logger to produce plain-text messages at various log levels (DEBUG, INFO, ERROR, etc.), allowing it to handle messages with a higher priority differently from those with a lower priority.Following is an example explaining the same −
import logging logging = logging.getLogger("logger") logging.info("Python logging")
The message is internally converted into a LogRecord object and sent to a Handler object designated for this logger. The handler will then convert the LogRecord into a string using a Formatter and emit that string.
To disable logging from imported modules in Python we need to use the getLogger() function.
The getLogger() function
The name of the logger is the only argument that the getLogger() method accepts. If a name is provided, it produces a reference to a logger with that name; otherwise, it returns root. The same logger object will be referenced by several calls to getLogger() with the same name.
You can modify the logger's log level that handles these messages. The request messages will be removed if the level is set to WARNING, however errors and warnings will remain.
Following is an example to disable logging using getLogger() function −
import logging logging.getLogger("Python").setLevel(logging.WARNING) logging.getLogger("Coding").setLevel(logging.WARNING)
Note: You can also use imported module. name__ if you don't want to write the module name as a string. Replace logging.WARNING with logging.ERROR and logging.CRITICAL respectively as an option if you want to advance and only want to record messages that are errors or critically important.
Kickstart Your Career
Get certified by completing the courseGet Started