change matplotlib font manager logging level

This commit is contained in:
martin 2024-02-01 01:54:07 +08:00
parent 78c4565c89
commit 4432097969
3 changed files with 31 additions and 3 deletions

View File

@ -5,10 +5,12 @@
"""
import sys
import datetime
import logging
import numpy as np
import matplotlib
from pylab import Rectangle, gca, figure, ylabel, axes, draw
from matplotlib import rcParams
from matplotlib.font_manager import FontManager, _log as fm_logger
from matplotlib.lines import Line2D, TICKLEFT, TICKRIGHT
from matplotlib.ticker import FuncFormatter, FixedLocator
@ -25,13 +27,14 @@ def set_mpl_params():
rcParams['font.family'] = 'sans-serif'
rcParams['axes.unicode_minus'] = False
expected_fonts = ['Microsoft YaHei', 'SimSun', 'SimHei', 'Noto Sans CJK JP']
expected_fonts = ['Microsoft YaHei', 'SimSun', 'SimHei', 'Source Han Sans CN', 'Noto Sans CJK JP']
current_fonts = matplotlib.rcParams['font.sans-serif']
for font in expected_fonts:
if font in current_fonts:
return
all_fonts = [f.name for f in matplotlib.font_manager.FontManager().ttflist]
with LoggingContext(fm_logger, level=logging.WARNING):
all_fonts = [f.name for f in FontManager().ttflist]
for font in expected_fonts:
if font in all_fonts:
current_fonts.insert(0, font)

View File

@ -40,4 +40,5 @@ __all__ = [
'hku_fatal_if',
'with_trace',
'capture_multiprocess_all_logger',
'LoggingContext',
]

View File

@ -205,4 +205,28 @@ def capture_multiprocess_all_logger(queue, level=None):
logger = logging.getLogger(name)
logger.addHandler(qh)
if level is not None:
logger.setLevel(level)
logger.setLevel(level)
# Temporary change logger level
# https://docs.python.org/3/howto/logging-cookbook.html
class LoggingContext:
def __init__(self, logger, level=None, handler=None, close=True):
self.logger = logger
self.level = level
self.handler = handler
self.close = close
def __enter__(self):
if self.level is not None:
self.old_level = self.logger.level
self.logger.setLevel(self.level)
if self.handler:
self.logger.addHandler(self.handler)
def __exit__(self, et, ev, tb):
if self.level is not None:
self.logger.setLevel(self.old_level)
if self.handler:
self.logger.removeHandler(self.handler)
if self.handler and self.close:
self.handler.close()