Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Bug]: matplotlib.set_loglevel() adds a console handler #23646

Closed
@l-johnston

Description

@l-johnston

Bug summary

matplotlib.set_loglevel() adds a logging console handler which then leads to duplicate messages in application code. The best practice is to allow the application code to add the handlers to its logger along with formatting, filtering, etc. The existing #13264 attempted to address this.

Code for reproduction

import logging
import matplotlib as mpl
mpl_logger = logging.getLogger("matplotlib")
mpl.set_loglevel("debug")
mpl_logger.hasHandlers()
logger = logging.getLogger()
ch = logging.StreamHandler()
logger.addHandler(ch)
logger.setLevel(logging.DEBUG)
import matplotlib.pyplot as plt

Actual outcome

True
DEBUG:matplotlib:CACHEDIR=C:\Users\ljohnsto.matplotlib
CACHEDIR=C:\Users\ljohnsto.matplotlib
DEBUG:matplotlib.font_manager:Using fontManager instance from C:\Users\ljohnsto.matplotlib\fontlist-v330.json
Using fontManager instance from C:\Users\ljohnsto.matplotlib\fontlist-v330.json

Expected outcome

False
CACHEDIR=C:\Users\ljohnsto.matplotlib
Using fontManager instance from C:\Users\ljohnsto.matplotlib\fontlist-v330.json

Additional information

The workaround is:

In [1]: import logging
In [2]: import matplotlib as mpl
In [3]: mpl_logger = logging.getLogger("matplotlib")
In [4]: mpl.set_loglevel("debug")
In [5]: mpl_logger_handlers = mpl_logger.handlers.copy()
In [6]: for h in mpl_logger_handlers:
   ...:     mpl_logger.removeHandler(h)
   ...:
In [7]: logger = logging.getLogger()
In [8]: ch = logging.StreamHandler()
In [9]: logger.addHandler(ch)
In [10]: logger.setLevel(logging.DEBUG)
In [11]: import matplotlib.pyplot as plt
CACHEDIR=C:\Users\ljohnsto\.matplotlib
Using fontManager instance from C:\Users\ljohnsto\.matplotlib\fontlist-v330.json
'''

### Operating system

Windows

### Matplotlib Version

3.5.2

### Matplotlib Backend

TkAgg

### Python version

3.9.13

### Jupyter version

_No response_

### Installation

pip

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions