1 # Copyright 2015 gRPC authors.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """A thread pool that logs exceptions raised by tasks executed within it."""
18 from concurrent import futures
20 _LOGGER = logging.getLogger(__name__)
24 """Wraps an arbitrary callable behavior in exception-logging."""
26 def _wrapping(*args, **kwargs):
28 return behavior(*args, **kwargs)
31 'Unexpected exception from %s executed in logging pool!',
38 class _LoggingPool(object):
39 """An exception-logging futures.ThreadPoolExecutor-compatible thread pool."""
41 def __init__(self, backing_pool):
42 self._backing_pool = backing_pool
47 def __exit__(self, exc_type, exc_val, exc_tb):
48 self._backing_pool.shutdown(wait=True)
50 def submit(self, fn, *args, **kwargs):
51 return self._backing_pool.submit(_wrap(fn), *args, **kwargs)
53 def map(self, func, *iterables, **kwargs):
54 return self._backing_pool.map(_wrap(func),
56 timeout=kwargs.get('timeout', None))
58 def shutdown(self, wait=True):
59 self._backing_pool.shutdown(wait=wait)
62 def pool(max_workers):
63 """Creates a thread pool that logs exceptions raised by the tasks within it.
66 max_workers: The maximum number of worker threads to allow the pool.
69 A futures.ThreadPoolExecutor-compatible thread pool that logs exceptions
70 raised by the tasks executed within it.
72 return _LoggingPool(futures.ThreadPoolExecutor(max_workers))