0

I made a logger in my python script (myscript.py),

logfmt = '[%(asctime)s]{%(filename)s:%(lineno)d}[%(levelname)s] %(message)s'
datefmt = '%Y-%m-%dT%H:%M:%S'
formatter = logging.Formatter(logfmt, datefmt=datefmt)
logging.basicConfig(level=logging.DEBUG, format=logfmt, datefmt=datefmt)
logger = logging.getLogger(name='mine')

At INFO level, it looks ok. But at DEBUG level, it's strange matplotlib prints its logs showing a very long list of modules it imported. How to prevent it and print the logs of my script only?

[2021-07-27T11:53:48]{myscript.py:183}[INFO] ...

[2021-07-27T11:53:48]{__init__.py:224}[DEBUG] matplotlib data path: /home/user/anaconda3/lib/python3.8/site-packages/matplotlib/mpl-data
[2021-07-27T11:53:48]{__init__.py:224}[DEBUG] CONFIGDIR=/home/user/.config/matplotlib
[2021-07-27T11:53:48]{__init__.py:1394}[DEBUG] matplotlib version 3.4.2
[2021-07-27T11:53:48]{__init__.py:1395}[DEBUG] interactive is False
[2021-07-27T11:53:48]{__init__.py:1396}[DEBUG] platform is linux
[2021-07-27T11:53:48]{__init__.py:1397}[DEBUG] loaded modules: ['sys', 'builtins', '_frozen_importlib', '_imp', '_warnings', '_frozen_importlib_external', '_io', 'marshal', 'posix', '_thread', '_weakref', 'time', 'zipimport', '_codecs', 'codecs', 'encodings.aliases', 'encodings', 'encodings.utf_8', '_signal', '__main__', 'encodings.latin_1', '_abc', 'abc', 'io', '_stat', 'stat', '_collections_abc', 
... very only list ...
'cycler', 'matplotlib.rcsetup', 'matplotlib._version', 'matplotlib.ft2font', 'kiwisolver', 'dateutil.rrule', 'matplotlib.units', 'matplotlib.dates']

[2021-07-27T11:53:48]{myscript.py:351}[INFO] ...
vvvvv
  • 25,404
  • 19
  • 49
  • 81
wsdzbm
  • 3,096
  • 3
  • 25
  • 28
  • Does this answer your question? [Python Logging - Disable logging from imported modules](https://stackoverflow.com/questions/35325042/python-logging-disable-logging-from-imported-modules) – blues Jul 27 '21 at 11:20
  • @blues no. and many comments of that A told that giving the logger a name doesn't change anything - same as my test. – wsdzbm Jul 27 '21 at 13:04
  • Did you actually try? basicConfig adds a handler to the root logger, so the proposed solution does not work with basicConfig. – blues Jul 27 '21 at 13:07

3 Answers3

2

Get the logger used by matplotlib, then override its log level:

logging.getLogger(name='matplotlib').setLevel(logging.WARNING)

Check How to list all existing loggers using python.logging module if you want to know how I found out the name of the matplotlib logger (which happens to be the same name as the module and the package, but it doesn't have to be).

Thomas
  • 174,939
  • 50
  • 355
  • 478
1

Don't have a setup to try this, hopefully still works. After your logging config add:

mpl_logger = logging.getLogger(‘matplotlib’)
mpl_logger.setLevel(logging.WARNING) 
0

Just set the loglevel of matplotlib to "info" see https://matplotlib.org/stable/_modules/matplotlib.html#set_loglevel

balderman
  • 22,927
  • 7
  • 34
  • 52