summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorMario Corchero <mcorcherojim@bloomberg.net>2022-01-24 12:39:50 (GMT)
committerGitHub <noreply@github.com>2022-01-24 12:39:50 (GMT)
commitd7c68639795a576ff58b6479c8bb34c113df3618 (patch)
treecb14dbe941f837f0c36f785c59d9d22b9d1fccca /Lib
parent58f3d980989c7346ad792d464c1d749dcec6af63 (diff)
downloadcpython-d7c68639795a576ff58b6479c8bb34c113df3618.zip
cpython-d7c68639795a576ff58b6479c8bb34c113df3618.tar.gz
cpython-d7c68639795a576ff58b6479c8bb34c113df3618.tar.bz2
bpo-41906: Accept built filters in dictConfig (GH-30756)
When configuring the logging stack, accept already built filters (or just callables) in the filters array of loggers and handlers. This facilitates passing quick callables as filters. Automerge-Triggered-By: GH:vsajip
Diffstat (limited to 'Lib')
-rw-r--r--Lib/logging/config.py6
-rw-r--r--Lib/test/test_logging.py38
2 files changed, 43 insertions, 1 deletions
diff --git a/Lib/logging/config.py b/Lib/logging/config.py
index 9bc07ed..86a1e4e 100644
--- a/Lib/logging/config.py
+++ b/Lib/logging/config.py
@@ -694,7 +694,11 @@ class DictConfigurator(BaseConfigurator):
"""Add filters to a filterer from a list of names."""
for f in filters:
try:
- filterer.addFilter(self.config['filters'][f])
+ if callable(f) or callable(getattr(f, 'filter', None)):
+ filter_ = f
+ else:
+ filter_ = self.config['filters'][f]
+ filterer.addFilter(filter_)
except Exception as e:
raise ValueError('Unable to add filter %r' % f) from e
diff --git a/Lib/test/test_logging.py b/Lib/test/test_logging.py
index 7c38676..4f33151 100644
--- a/Lib/test/test_logging.py
+++ b/Lib/test/test_logging.py
@@ -3447,6 +3447,44 @@ class ConfigDictTest(BaseTest):
logging.info('some log')
self.assertEqual(stderr.getvalue(), 'some log my_type\n')
+ def test_config_callable_filter_works(self):
+ def filter_(_):
+ return 1
+ self.apply_config({
+ "version": 1, "root": {"level": "DEBUG", "filters": [filter_]}
+ })
+ assert logging.getLogger().filters[0] is filter_
+ logging.getLogger().filters = []
+
+ def test_config_filter_works(self):
+ filter_ = logging.Filter("spam.eggs")
+ self.apply_config({
+ "version": 1, "root": {"level": "DEBUG", "filters": [filter_]}
+ })
+ assert logging.getLogger().filters[0] is filter_
+ logging.getLogger().filters = []
+
+ def test_config_filter_method_works(self):
+ class FakeFilter:
+ def filter(self, _):
+ return 1
+ filter_ = FakeFilter()
+ self.apply_config({
+ "version": 1, "root": {"level": "DEBUG", "filters": [filter_]}
+ })
+ assert logging.getLogger().filters[0] is filter_
+ logging.getLogger().filters = []
+
+ def test_invalid_type_raises(self):
+ class NotAFilter: pass
+ for filter_ in [None, 1, NotAFilter()]:
+ self.assertRaises(
+ ValueError,
+ self.apply_config,
+ {"version": 1, "root": {"level": "DEBUG", "filters": [filter_]}}
+ )
+
+
class ManagerTest(BaseTest):
def test_manager_loggerclass(self):
logged = []