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")"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.

Updated on: 14-Nov-2022

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started