Skip to content

Commit

Permalink
Merge d713086 into 237bb96
Browse files Browse the repository at this point in the history
  • Loading branch information
cjrh committed Sep 16, 2018
2 parents 237bb96 + d713086 commit e0a3020
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
14 changes: 11 additions & 3 deletions aiologfields.py
Expand Up @@ -24,19 +24,27 @@
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()

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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions tests/test_main.py
Expand Up @@ -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()

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down

0 comments on commit e0a3020

Please sign in to comment.