Skip to content

Commit

Permalink
configure_log(): allow level setting on a per Logger basis
Browse files Browse the repository at this point in the history
  • Loading branch information
RayPlante committed Nov 28, 2024
1 parent 59d6f83 commit ebb6f15
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
10 changes: 9 additions & 1 deletion python/nistoar/base/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ def configure_log(logfile: str=None, level: int=None, format: str=None, config:
level = _log_levels_byname.get(str(level), level)
if not isinstance(level, int):
raise ConfigurationException("Unrecognized loglevel value: "+str(level))

if not format:
format = config.get('logformat', LOG_FORMAT)
frmtr = logging.Formatter(format)
Expand All @@ -180,6 +180,14 @@ def configure_log(logfile: str=None, level: int=None, format: str=None, config:
if level >= logging.DEBUG:
logging.getLogger("filelock").setLevel(level+10)

# config can set levels on a per-logname basis
if config.get("loglevelsfor") and isinstance(config.get("loglevelsfor"), Mapping):
for lognm, level in config.get("loglevelsfor", {}).items():
if not isinstance(level, int):
level = _log_levels_byname.get(str(level), level)
if isinstance(level, int):
logging.getLogger(lognm).setLevel(level)

if addstderr:
if not isinstance(addstderr, str):
addstderr = format
Expand Down
11 changes: 10 additions & 1 deletion python/tests/nistoar/base/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,10 @@ def test_from_config(self):
cfg = {
'logdir': tmpd,
'logfile': logfile,
'loglevel': 'DEBUG'
'loglevel': 'DEBUG',
'loglevelsfor': {
'pymongo': 'INFO'
}
}

self.logfile = os.path.join(tmpd, logfile)
Expand All @@ -132,11 +135,17 @@ def test_from_config(self):
self.assertEqual(config.global_logdir, tmpd)
self.assertEqual(config.global_logfile, self.logfile)

self.assertEqual(self.rootlog.getEffectiveLevel(), logging.DEBUG-1)
self.assertEqual(config._log_handler.level, logging.DEBUG)
self.assertEqual(logging.getLogger("pymongo").getEffectiveLevel(), logging.INFO)

self.rootlog.warning('Oops')
self.assertTrue(os.path.exists(self.logfile))
with open(self.logfile) as fd:
words = fd.read()
self.assertIn("Oops", words)



def test_abs(self):
self.logfile = os.path.join(tmpd, "cfgfile.log")
Expand Down

0 comments on commit ebb6f15

Please sign in to comment.