From d713086c8010bfec4ce1c9f0894953a4544f8bea Mon Sep 17 00:00:00 2001 From: Caleb Hattingh Date: Sun, 16 Sep 2018 16:46:36 +1000 Subject: [PATCH] Handle 3.7 code, deprecation warnings asyncio.Task.current_task --- aiologfields.py | 14 +++++++++++--- tests/test_main.py | 6 +++--- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/aiologfields.py b/aiologfields.py index fc8f38f..6129cf9 100644 --- a/aiologfields.py +++ b/aiologfields.py @@ -24,11 +24,19 @@ import logging from types import SimpleNamespace from copy import deepcopy +import sys INSTALLED = False +def get_current_task(*args, **kwargs): # pragma: no cover + if sys.version_info < (3, 7): + return asyncio.Task.current_task(*args, **kwargs) + else: + return asyncio.current_task(*args, **kwargs) + + def _record_factory_factory(task_attr='logging_fields'): old_factory = logging.getLogRecordFactory() @@ -36,7 +44,7 @@ def _record_factory_factory(task_attr='logging_fields'): def _record_factory(*args, **kwargs): record = old_factory(*args, **kwargs) try: - t = asyncio.Task.current_task() + t = get_current_task() except RuntimeError: pass # No loop in this thread. Don't worry about it. else: @@ -70,7 +78,7 @@ def _new_task_factory(loop, coro): # If there are fields on the CURRENT task, copy them over to this # task. - current_task = asyncio.Task.current_task() + current_task = get_current_task(loop=loop) if current_task: current_attr = getattr(current_task, task_attr, None) if current_attr: @@ -115,7 +123,7 @@ def set_fields(task: asyncio.Task = None, task_attr='logging_fields', **kwargs): - The new task factory should already have been set up, typically via ``aiologfields.install()`` """ - t = task or asyncio.Task.current_task() + t = task or get_current_task() if t and hasattr(t, task_attr): attr = getattr(t, task_attr) assert isinstance(attr, SimpleNamespace) diff --git a/tests/test_main.py b/tests/test_main.py index 64a4f16..6627b59 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -13,7 +13,7 @@ async def cf2(): logger.info('blah blah') async def cf1(): - ct = asyncio.Task.current_task() + ct = aiologfields.get_current_task() ct.logging_fields.correlation_id = correlation_id await cf2() @@ -68,7 +68,7 @@ async def cf2(): logger.info('hey') async def cf1(): - ct = asyncio.Task.current_task() + ct = aiologfields.get_current_task() ct.logging_fields.correlation_id = correlation_id t = loop.create_task(cf2()) await t @@ -91,7 +91,7 @@ async def cf2(): await loop.run_in_executor(None, thread_func) async def cf1(): - ct = asyncio.Task.current_task() + ct = aiologfields.get_current_task() ct.logging_fields.correlation_id = correlation_id t = loop.create_task(cf2()) await t