Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 31 additions & 10 deletions src/structlog/_native.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,12 @@
NOTSET,
WARNING,
)
from .contextvars import _ASYNC_CALLING_STACK, _ASYNC_CALLING_THREAD
from .contextvars import (
_ASYNC_CALLING_STACK,
_ASYNC_CALLING_TASK_NAME,
_ASYNC_CALLING_THREAD,
_get_current_task_name,
)
from .typing import FilteringBoundLogger


Expand Down Expand Up @@ -65,6 +70,7 @@ async def aexception(
thread_token = _ASYNC_CALLING_THREAD.set(
(threading.get_ident(), threading.current_thread().name)
)
task_name_token = _ASYNC_CALLING_TASK_NAME.set(_get_current_task_name())
scs_token = _ASYNC_CALLING_STACK.set(sys._getframe().f_back) # type: ignore[arg-type]
ctx = contextvars.copy_context()

Expand All @@ -76,6 +82,7 @@ async def aexception(
finally:
_ASYNC_CALLING_STACK.reset(scs_token)
_ASYNC_CALLING_THREAD.reset(thread_token)
_ASYNC_CALLING_TASK_NAME.reset(task_name_token)

return runner

Expand Down Expand Up @@ -184,6 +191,9 @@ async def ameth(self: Any, event: str, *args: Any, **kw: Any) -> Any:
thread_token = _ASYNC_CALLING_THREAD.set(
(threading.get_ident(), threading.current_thread().name)
)
task_name_token = _ASYNC_CALLING_TASK_NAME.set(
_get_current_task_name()
)
scs_token = _ASYNC_CALLING_STACK.set(sys._getframe().f_back) # type: ignore[arg-type]
ctx = contextvars.copy_context()

Expand All @@ -197,6 +207,7 @@ async def ameth(self: Any, event: str, *args: Any, **kw: Any) -> Any:
finally:
_ASYNC_CALLING_STACK.reset(scs_token)
_ASYNC_CALLING_THREAD.reset(thread_token)
_ASYNC_CALLING_TASK_NAME.reset(task_name_token)

meth.__name__ = name
ameth.__name__ = f"a{name}"
Expand Down Expand Up @@ -228,6 +239,9 @@ async def alog(
thread_token = _ASYNC_CALLING_THREAD.set(
(threading.get_ident(), threading.current_thread().name)
)
task_name_token = _ASYNC_CALLING_TASK_NAME.set(
_get_current_task_name()
)
scs_token = _ASYNC_CALLING_STACK.set(sys._getframe().f_back) # type: ignore[arg-type]
ctx = contextvars.copy_context()

Expand All @@ -241,21 +255,28 @@ async def alog(
finally:
_ASYNC_CALLING_STACK.reset(scs_token)
_ASYNC_CALLING_THREAD.reset(thread_token)
_ASYNC_CALLING_TASK_NAME.reset(task_name_token)

return runner

meths: dict[str, Callable[..., Any]] = {"log": log, "alog": alog}
meths: dict[str, Callable[..., Any]] = {
"log": log,
"alog": alog,
"exception": exception,
"aexception": aexception,
}
for lvl, name in LEVEL_TO_NAME.items():
meths[name], meths[f"a{name}"] = make_method(lvl)

meths["exception"] = exception
meths["aexception"] = aexception
meths["fatal"] = meths["critical"]
meths["afatal"] = meths["acritical"]
meths["warn"] = meths["warning"]
meths["awarn"] = meths["awarning"]
meths["msg"] = meths["info"]
meths["amsg"] = meths["ainfo"]
for alias, target in [
("fatal", "critical"),
("afatal", "acritical"),
("warn", "warning"),
("awarn", "awarning"),
("msg", "info"),
("amsg", "ainfo"),
]:
meths[alias] = meths[target]

# Introspection
meths["is_enabled_for"] = lambda self, level: level >= min_level
Expand Down
18 changes: 18 additions & 0 deletions src/structlog/contextvars.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

from __future__ import annotations

import asyncio
import contextlib
import contextvars

Expand All @@ -44,6 +45,23 @@
contextvars.ContextVar("_ASYNC_CALLING_THREAD")
)

_ASYNC_CALLING_TASK_NAME: contextvars.ContextVar[str | None] = (
contextvars.ContextVar("_ASYNC_CALLING_TASK_NAME", default=None)
)


def _get_current_task_name() -> str | None:
try:
task = asyncio.current_task()
except RuntimeError:
return None

if task is None:
return None

return task.get_name()


# For proper isolation, we have to use a dict of ContextVars instead of a
# single ContextVar with a dict.
# See https://github.com/hynek/structlog/pull/302 for details.
Expand Down
22 changes: 19 additions & 3 deletions src/structlog/processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@
)
from ._log_levels import NAME_TO_LEVEL, add_log_level
from ._utils import get_processname
from .contextvars import _ASYNC_CALLING_THREAD
from .contextvars import (
_ASYNC_CALLING_TASK_NAME,
_ASYNC_CALLING_THREAD,
_get_current_task_name,
)
from .tracebacks import ExceptionDictTransformer
from .typing import (
EventDict,
Expand Down Expand Up @@ -775,6 +779,8 @@ class CallsiteParameter(enum.Enum):
PROCESS = "process"
#: The name of the process the callsite was executed in.
PROCESS_NAME = "process_name"
#: The name of the asyncio task the callsite was executed in.
TASK_NAME = "task_name"


def _get_callsite_pathname(module: str, frame: FrameType) -> Any:
Expand Down Expand Up @@ -829,6 +835,14 @@ def _get_callsite_process_name(module: str, frame: FrameType) -> Any:
return get_processname()


def _get_callsite_task_name(module: str, frame: FrameType) -> Any:
task_name = _ASYNC_CALLING_TASK_NAME.get(None)
if task_name is not None:
return task_name

return _get_current_task_name()


class CallsiteParameterAdder:
"""
Adds parameters of the callsite that an event dictionary originated from to
Expand Down Expand Up @@ -884,6 +898,7 @@ class CallsiteParameterAdder:
CallsiteParameter.THREAD_NAME: _get_callsite_thread_name,
CallsiteParameter.PROCESS: _get_callsite_process,
CallsiteParameter.PROCESS_NAME: _get_callsite_process_name,
CallsiteParameter.TASK_NAME: _get_callsite_task_name,
}
_record_attribute_map: ClassVar[dict[CallsiteParameter, str]] = {
CallsiteParameter.PATHNAME: "pathname",
Expand All @@ -895,6 +910,7 @@ class CallsiteParameterAdder:
CallsiteParameter.THREAD_NAME: "threadName",
CallsiteParameter.PROCESS: "process",
CallsiteParameter.PROCESS_NAME: "processName",
CallsiteParameter.TASK_NAME: "taskName",
}

_all_parameters: ClassVar[set[CallsiteParameter]] = set(CallsiteParameter)
Expand Down Expand Up @@ -944,9 +960,9 @@ def __call__(
# then the callsite parameters of the record will not be correct.
if record is not None and not from_structlog:
for mapping in self._record_mappings:
event_dict[mapping.event_dict_key] = record.__dict__[
event_dict[mapping.event_dict_key] = record.__dict__.get(
mapping.record_attribute
]
)

return event_dict

Expand Down
10 changes: 10 additions & 0 deletions src/structlog/stdlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@
from ._log_levels import LEVEL_TO_NAME, NAME_TO_LEVEL, add_log_level
from .contextvars import (
_ASYNC_CALLING_STACK,
_ASYNC_CALLING_TASK_NAME,
_ASYNC_CALLING_THREAD,
_get_current_task_name,
merge_contextvars,
)
from .exceptions import DropEvent
Expand Down Expand Up @@ -458,6 +460,9 @@ async def _dispatch_to_sync(
thread_token = _ASYNC_CALLING_THREAD.set(
(threading.get_ident(), threading.current_thread().name)
)
task_name_token = _ASYNC_CALLING_TASK_NAME.set(
_get_current_task_name()
)
scs_token = _ASYNC_CALLING_STACK.set(sys._getframe().f_back.f_back) # type: ignore[union-attr, arg-type, unused-ignore]
ctx = contextvars.copy_context()

Expand All @@ -469,6 +474,7 @@ async def _dispatch_to_sync(
finally:
_ASYNC_CALLING_STACK.reset(scs_token)
_ASYNC_CALLING_THREAD.reset(thread_token)
_ASYNC_CALLING_TASK_NAME.reset(task_name_token)

async def adebug(self, event: str, *args: Any, **kw: Any) -> None:
"""
Expand Down Expand Up @@ -666,6 +672,9 @@ async def _dispatch_to_sync(
thread_token = _ASYNC_CALLING_THREAD.set(
(threading.get_ident(), threading.current_thread().name)
)
task_name_token = _ASYNC_CALLING_TASK_NAME.set(
_get_current_task_name()
)
scs_token = _ASYNC_CALLING_STACK.set(sys._getframe().f_back.f_back) # type: ignore[union-attr, arg-type, unused-ignore]
ctx = contextvars.copy_context()

Expand All @@ -677,6 +686,7 @@ async def _dispatch_to_sync(
finally:
_ASYNC_CALLING_STACK.reset(scs_token)
_ASYNC_CALLING_THREAD.reset(thread_token)
_ASYNC_CALLING_TASK_NAME.reset(task_name_token)

async def debug(self, event: str, *args: Any, **kw: Any) -> None:
await self._dispatch_to_sync(self.sync_bl.debug, event, args, kw)
Expand Down
Loading