Skip to content

Commit 1bece33

Browse files
committed
1) Switched between logging.warning <-> cbook._warn_external.
2) Started using _log. instead of logging. 3) Formated warning messages so they appear nicer.
1 parent b00921b commit 1bece33

39 files changed

+227
-212
lines changed

lib/matplotlib/__init__.py

+30-35
Original file line numberDiff line numberDiff line change
@@ -244,9 +244,8 @@ def _set_logger_verbose_level(level_str='silent', file_str='sys.stdout'):
244244
fileo = open(file_str, 'w')
245245
# if this fails, we will just write to stdout
246246
except IOError:
247-
logging.warning('could not open log file "{0}"'
248-
'for writing. Check your '
249-
'matplotlibrc'.format(file_str))
247+
_log.warning('could not open log file "{0}" for writing. '
248+
'Check your matplotlibrc'.format(file_str))
250249
console = logging.StreamHandler(fileo)
251250
console.setLevel(newlev)
252251
_log.addHandler(console)
@@ -307,10 +306,9 @@ def set_level(self, level):
307306
if self._commandLineVerbose is not None:
308307
level = self._commandLineVerbose
309308
if level not in self.levels:
310-
cbook._warn_external(
311-
'matplotlib: unrecognized --verbose-* string "%s". Legal '
312-
'values are %s' % (
313-
level, self.levels))
309+
cbook._warn_external('matplotlib: unrecognized --verbose-* '
310+
'string "%s". Legal values are %s' %
311+
(level, self.levels))
314312
else:
315313
self.level = level
316314

@@ -489,10 +487,9 @@ def checkdep_ps_distiller(s):
489487
gs_exec, gs_v = checkdep_ghostscript()
490488
if not gs_exec:
491489
flag = False
492-
493-
logging.warning('matplotlibrc ps.usedistiller option can not be used '
494-
'unless ghostscript 9.0 or later is installed on your '
495-
'system')
490+
_log.warning('matplotlibrc ps.usedistiller option can not be used '
491+
'unless ghostscript 9.0 or later is installed on your '
492+
'system')
496493

497494
if s == 'xpdf':
498495
pdftops_req = '3.0'
@@ -505,9 +502,9 @@ def checkdep_ps_distiller(s):
505502
pass
506503
else:
507504
flag = False
508-
logging.warning(('matplotlibrc ps.usedistiller can not be set to '
509-
'xpdf unless xpdf-%s or later is installed on '
510-
'your system') % pdftops_req)
505+
_log.warning(('matplotlibrc ps.usedistiller can not be set to '
506+
'xpdf unless xpdf-%s or later is installed on '
507+
'your system') % pdftops_req)
511508

512509
if flag:
513510
return s
@@ -525,23 +522,22 @@ def checkdep_usetex(s):
525522

526523
if shutil.which("tex") is None:
527524
flag = False
528-
logging.warning(
529-
'matplotlibrc text.usetex option can not be used unless TeX is '
530-
'installed on your system')
525+
_log.warning('matplotlibrc text.usetex option can not be used unless '
526+
'TeX is installed on your system')
531527

532528
dvipng_v = checkdep_dvipng()
533529
if not compare_versions(dvipng_v, dvipng_req):
534530
flag = False
535-
logging.warning('matplotlibrc text.usetex can not be used with *Agg '
536-
'backend unless dvipng-%s or later is installed on '
537-
'your system' % dvipng_req)
531+
_log.warning('matplotlibrc text.usetex can not be used with *Agg '
532+
'backend unless dvipng-%s or later is installed on '
533+
'your system' % dvipng_req)
538534

539535
gs_exec, gs_v = checkdep_ghostscript()
540536
if not compare_versions(gs_v, gs_req):
541537
flag = False
542-
logging.warning('matplotlibrc text.usetex can not be used unless '
543-
'ghostscript-%s or later is installed on your system'
544-
% gs_req)
538+
_log.warning('matplotlibrc text.usetex can not be used unless '
539+
'ghostscript-%s or later is installed on your system'
540+
% gs_req)
545541

546542
return flag
547543

@@ -958,17 +954,17 @@ def _rc_params_in_file(fname, fail_on_error=False):
958954
tup = strippedline.split(':', 1)
959955
if len(tup) != 2:
960956
error_details = _error_details_fmt % (cnt, line, fname)
961-
logging.warning('Illegal %s' % error_details)
957+
_log.warning('Illegal %s' % error_details)
962958
continue
963959
key, val = tup
964960
key = key.strip()
965961
val = val.strip()
966962
if key in rc_temp:
967-
logging.warning('Duplicate key in file "%s", line #%d' %
963+
_log.warning('Duplicate key in file "%s", line #%d' %
968964
(fname, cnt))
969965
rc_temp[key] = (val, line, cnt)
970966
except UnicodeDecodeError:
971-
logging.warning(
967+
_log.warning(
972968
('Cannot decode configuration file %s with '
973969
'encoding %s, check LANG and LC_* variables')
974970
% (fname, locale.getpreferredencoding(do_setlocale=False) or
@@ -987,8 +983,8 @@ def _rc_params_in_file(fname, fail_on_error=False):
987983
config[key] = val # try to convert to proper type or skip
988984
except Exception as msg:
989985
error_details = _error_details_fmt % (cnt, line, fname)
990-
logging.warning('Bad val "%s" on %s\n\t%s' %
991-
(val, error_details, msg))
986+
_log.warning('Bad val "%s" on %s\n\t%s' %
987+
(val, error_details, msg))
992988

993989
for key, (val, line, cnt) in rc_temp.items():
994990
if key in defaultParams:
@@ -999,8 +995,8 @@ def _rc_params_in_file(fname, fail_on_error=False):
999995
config[key] = val # try to convert to proper type or skip
1000996
except Exception as msg:
1001997
error_details = _error_details_fmt % (cnt, line, fname)
1002-
logging.warning('Bad val "%s" on %s\n\t%s' %
1003-
(val, error_details, msg))
998+
_log.warning('Bad val "%s" on %s\n\t%s' %
999+
(val, error_details, msg))
10041000
elif key in _deprecated_ignore_map:
10051001
version, alt_key = _deprecated_ignore_map[key]
10061002
cbook.warn_deprecated(
@@ -1424,7 +1420,7 @@ def _init_tests():
14241420
from matplotlib import ft2font
14251421
if (ft2font.__freetype_version__ != LOCAL_FREETYPE_VERSION or
14261422
ft2font.__freetype_build_type__ != 'local'):
1427-
logging.warning(
1423+
_log.warning(
14281424
"Matplotlib is not built with the correct FreeType version to run "
14291425
"tests. Set local_freetype=True in setup.cfg and rebuild. "
14301426
"Expect many image comparison failures below. "
@@ -1765,10 +1761,9 @@ def inner(ax, *args, data=None, **kwargs):
17651761
else:
17661762
cbook._warn_external(
17671763
"Tried to set a label via parameter %r in func %r but "
1768-
"couldn't find such an argument.\n"
1769-
"(This is a programming error, please report to "
1770-
"the Matplotlib list!)" % (label_namer,
1771-
func.__name__),
1764+
"couldn't find such an argument.\n(This is a "
1765+
"programming error, please report to the Matplotlib "
1766+
"list!)" % (label_namer, func.__name__),
17721767
RuntimeWarning)
17731768
return func(ax, *args, **kwargs)
17741769

lib/matplotlib/_constrained_layout.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -154,8 +154,8 @@ def do_constrained_layout(fig, renderer, h_pad, w_pad,
154154
gss.add(gs)
155155
if len(gss) == 0:
156156
cbook._warn_external('There are no gridspecs with layoutboxes. '
157-
'Possibly did not call parent GridSpec with the figure= '
158-
'keyword')
157+
'Possibly did not call parent GridSpec with the'
158+
' figure= keyword')
159159

160160
if fig._layoutbox.constrained_layout_called < 1:
161161
for gs in gss:
@@ -221,8 +221,8 @@ def do_constrained_layout(fig, renderer, h_pad, w_pad,
221221
# so this does the same w/o zeroing layout.
222222
ax._set_position(newpos, which='original')
223223
else:
224-
cbook._warn_ext('constrained_layout not applied. At least '
225-
'one axes collapsed to zero width or height.')
224+
cbook._warn_external('constrained_layout not applied. At least '
225+
'one axes collapsed to zero width or height.')
226226

227227

228228
def _make_ghost_gridspec_slots(fig, gs):

lib/matplotlib/artist.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
from .transforms import (Bbox, IdentityTransform, Transform, TransformedBbox,
1414
TransformedPatchPath, TransformedPath)
1515

16+
_log = logging.getLogger(__name__)
17+
1618

1719
def allow_rasterization(draw):
1820
"""
@@ -401,8 +403,7 @@ def contains(self, mouseevent):
401403
"""
402404
if callable(self._contains):
403405
return self._contains(self, mouseevent)
404-
logging.warning("'%s' needs 'contains' method" %
405-
self.__class__.__name__)
406+
_log.warning("'%s' needs 'contains' method" % self.__class__.__name__)
406407
return False, {}
407408

408409
def set_contains(self, picker):
@@ -852,7 +853,8 @@ def set_rasterized(self, rasterized):
852853
rasterized : bool or None
853854
"""
854855
if rasterized and not hasattr(self.draw, "_supports_rasterization"):
855-
logging.warning("Rasterization of '%s' will be ignored" % self)
856+
cbook._warn_external(
857+
"Rasterization of '%s' will be ignored" % self)
856858

857859
self._rasterized = rasterized
858860

lib/matplotlib/axes/_axes.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -4624,9 +4624,9 @@ def hexbin(self, x, y, C=None, gridsize=100, bins=None,
46244624
# Set normalizer if bins is 'log'
46254625
if bins == 'log':
46264626
if norm is not None:
4627-
cbook._warn_external(
4628-
"Only one of 'bins' and 'norm' arguments can be "
4629-
"supplied, ignoring bins={}".format(bins))
4627+
cbook._warn_external("Only one of 'bins' and 'norm' "
4628+
"arguments can be supplied, ignoring "
4629+
"bins={}".format(bins))
46304630
else:
46314631
norm = mcolors.LogNorm()
46324632
bins = None

lib/matplotlib/axis.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -1055,21 +1055,21 @@ def _update_ticks(self, renderer):
10551055
ds1 = self._get_pixel_distance_along_axis(
10561056
interval_expanded[0], -0.5)
10571057
except Exception:
1058-
cbook._warn_external(
1059-
"Unable to find pixel distance along axis for "
1060-
"interval padding of ticks; assuming no interval "
1061-
"padding needed.")
1058+
cbook._warn_external("Unable to find pixel distance "
1059+
"along axis for interval padding of "
1060+
"ticks; assuming no interval "
1061+
"padding needed.")
10621062
ds1 = 0.0
10631063
if np.isnan(ds1):
10641064
ds1 = 0.0
10651065
try:
10661066
ds2 = self._get_pixel_distance_along_axis(
10671067
interval_expanded[1], +0.5)
10681068
except Exception:
1069-
cbook._warn_external(
1070-
"Unable to find pixel distance along axis "
1071-
"for interval padding of ticks; assuming no "
1072-
"interval padding needed.")
1069+
cbook._warn_external("Unable to find pixel distance "
1070+
"along axis for interval padding of "
1071+
"ticks; assuming no interval "
1072+
"padding needed.")
10731073
ds2 = 0.0
10741074
if np.isnan(ds2):
10751075
ds2 = 0.0
@@ -1393,9 +1393,9 @@ def grid(self, b=None, which='major', **kwargs):
13931393
"""
13941394
if len(kwargs):
13951395
if not b and b is not None: # something false-like but not None
1396-
cbook._warn_external(
1397-
'First parameter to grid() is false, but line '
1398-
'properties are supplied. The grid will be enabled.')
1396+
cbook._warn_external('First parameter to grid() is false, '
1397+
'but line properties are supplied. The '
1398+
'grid will be enabled.')
13991399
b = True
14001400
which = which.lower()
14011401
if which not in ['major', 'minor', 'both']:

lib/matplotlib/backend_bases.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
from weakref import WeakKeyDictionary
4242

4343
import numpy as np
44+
import logging
4445

4546
from matplotlib import (
4647
backend_tools as tools, cbook, colors, textpath, tight_bbox, transforms,
@@ -61,6 +62,7 @@
6162
except ImportError:
6263
_has_pil = False
6364

65+
_log = logging.getLogger(__name__)
6466

6567
_default_filetypes = {
6668
'ps': 'Postscript',
@@ -2395,7 +2397,7 @@ def _get_uniform_gridstate(ticks):
23952397
try:
23962398
ax.set_yscale('log')
23972399
except ValueError as exc:
2398-
cbook._warn_external(str(exc))
2400+
_log.warning(str(exc))
23992401
ax.set_yscale('linear')
24002402
ax.figure.canvas.draw_idle()
24012403
# toggle scaling of x-axes between 'log and 'linear' (default key 'k')
@@ -2408,7 +2410,7 @@ def _get_uniform_gridstate(ticks):
24082410
try:
24092411
ax.set_xscale('log')
24102412
except ValueError as exc:
2411-
cbook._warn_external(str(exc))
2413+
_log.warning(str(exc))
24122414
ax.set_xscale('linear')
24132415
ax.figure.canvas.draw_idle()
24142416

lib/matplotlib/backend_managers.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
from matplotlib.rcsetup import validate_stringlist
1111
import matplotlib.backend_tools as tools
1212

13+
_log = logging.getLogger(__name__)
14+
1315

1416
class ToolEvent(object):
1517
"""Event for tool manipulation (add/remove)"""
@@ -53,10 +55,9 @@ class ToolManager(object):
5355
"""
5456

5557
def __init__(self, figure=None):
56-
logging.warning('Treat the new Tool classes introduced in v1.5 as'
57-
' experimental for now, the API will likely '
58-
'change in version 2.1 and perhaps the rcParam as'
59-
' well')
58+
_log.warning('Treat the new Tool classes introduced in v1.5 as '
59+
'experimental for now, the API will likely change in '
60+
'version 2.1 and perhaps the rcParam as well')
6061

6162
self._key_press_handler_id = None
6263

@@ -203,7 +204,7 @@ def update_keymap(self, name, *keys):
203204
for k in validate_stringlist(key):
204205
if k in self._keys:
205206
cbook._warn_external('Key %s changed from %s to %s' %
206-
(k, self._keys[k], name))
207+
(k, self._keys[k], name))
207208
self._keys[k] = name
208209

209210
def remove_tool(self, name):

lib/matplotlib/backend_tools.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
from matplotlib._pylab_helpers import Gcf
2323
import matplotlib.cbook as cbook
2424

25+
_log = logging.getLogger(__name__)
26+
2527

2628
class Cursors(object):
2729
"""Simple namespace for cursor reference"""
@@ -75,10 +77,9 @@ class ToolBase(object):
7577
"""
7678

7779
def __init__(self, toolmanager, name):
78-
logging.warning('Treat the new Tool classes introduced in v1.5 as'
79-
' experimental for now, the API will likely '
80-
'change in version 2.1, and some tools might '
81-
'change name')
80+
_log.warning('Treat the new Tool classes introduced in v1.5 as '
81+
'experimental for now, the API will likely change in '
82+
'version 2.1, and some tools might change name')
8283
self._name = name
8384
self._toolmanager = toolmanager
8485
self._figure = None

lib/matplotlib/backends/backend_pgf.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -399,8 +399,8 @@ def __init__(self, figure, fh, dummy=False):
399399
else:
400400
# if fh does not belong to a filename, deactivate draw_image
401401
if not hasattr(fh, 'name') or not os.path.exists(fh.name):
402-
logging.warning("streamed pgf-code does not support raster "
403-
"graphics, consider using the pgf-to-pdf option")
402+
_log.warning("streamed pgf-code does not support raster "
403+
"graphics, consider using the pgf-to-pdf option")
404404
self.__dict__["draw_image"] = lambda *args, **kwargs: None
405405

406406
def draw_markers(self, gc, marker_path, marker_trans, path, trans,

lib/matplotlib/backends/backend_webagg_core.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,13 @@
1818

1919
import numpy as np
2020
import tornado
21+
import logging
2122

2223
from matplotlib.backends import backend_agg
2324
from matplotlib.backend_bases import _Backend
24-
from matplotlib import backend_bases, _png, cbook
25+
from matplotlib import backend_bases, _png
2526

27+
_log = logging.getLogger(__name__)
2628

2729
# http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
2830
_SHIFT_LUT = {59: ':',
@@ -240,8 +242,8 @@ def handle_event(self, event):
240242
return handler(event)
241243

242244
def handle_unknown_event(self, event):
243-
cbook._warn_external('Unhandled message type {0}. {1}'.format(
244-
event['type'], event))
245+
_log.warning('Unhandled message type {0}. {1}'.format(
246+
event['type'], event))
245247

246248
def handle_ack(self, event):
247249
# Network latency tends to decrease if traffic is flowing

0 commit comments

Comments
 (0)