Skip to content

scope

scope #

The verbs, and to(), which decides where they go.

  1. to(*sinks) opens a fresh Log routed to the sinks and makes its root the ambient parent for the block; several sinks is the tee. Outside every to() block the verbs capture their call site, read the context variable and return an inert entry: nothing is recorded.
  2. info, warning, error and progress make an entry beneath the ambient parent; with on the result makes it the parent for its block. The caller's code location is the entry's slot inside an iterated progress loop (the loop rule in Log); key= names a slot by hand.
  3. A copy_context() thread — a pmap worker — inherits the ambient parent; a bare thread starts with none, though an entry it already holds still accepts update and advance.

current() #

The log being written in this context, if any.

Source code in capturegraph-lib/capturegraph/logging/scope.py
def current() -> Log | None:
    """The log being written in this context, if any."""
    scope = listening()
    return scope[1] if scope is not None else None

current_entry() #

The innermost open entry in this context, if any.

Source code in capturegraph-lib/capturegraph/logging/scope.py
def current_entry() -> Entry | None:
    """The innermost open entry in this context, if any."""
    scope = listening()
    if scope is None:
        return None
    parent, log = scope
    return parent if parent is not log.root else None

error(message, *, key=None, kind='text', **fields) #

Log message at error; see info.

Source code in capturegraph-lib/capturegraph/logging/scope.py
def error(
    message: str,
    *,
    key: str | None = None,
    kind: Kind = "text",
    **fields: JSONValue,
) -> Entry:
    """Log ``message`` at ``error``; see ``info``."""
    return _add("error", message, fields, key, kind, _site())

info(message, *, key=None, kind='text', **fields) #

Log message at info; with on the result nests a block beneath it.

with cg.logging.info("Decoding frames", count=len(frames)):
    ...

Parameters:

Name Type Description Default
message str

What happened.

required
key str | None

A slot of your own, so a later call with the same key revises this entry.

None
kind Kind

What message is: text, a shell command, or a program's output; renderers show each as such.

'text'
fields JSONValue

Named values the line carries.

{}
Source code in capturegraph-lib/capturegraph/logging/scope.py
def info(
    message: str,
    *,
    key: str | None = None,
    kind: Kind = "text",
    **fields: JSONValue,
) -> Entry:
    """Log ``message`` at ``info``; ``with`` on the result nests a block beneath it.

    ```python
    with cg.logging.info("Decoding frames", count=len(frames)):
        ...
    ```

    Args:
        message: What happened.
        key: A slot of your own, so a later call with the same key revises this entry.
        kind: What ``message`` is: ``text``, a shell ``command``, or a
            program's ``output``; renderers show each as such.
        fields: Named values the line carries.
    """
    return _add("info", message, fields, key, kind, _site())

label_of(function) #

The label a count takes from function: its name.

Source code in capturegraph-lib/capturegraph/logging/scope.py
def label_of(function: Callable[..., object]) -> str:
    """The label a count takes from ``function``: its name."""
    name = getattr(function, "__name__", None)
    return name if isinstance(name, str) else type(function).__name__

progress(iterable=None, *, total=None, label=None, key=None) #

A counted entry: iterate it, or hold it and advance it.

Iterating numbers the iterations, and inside the loop an entry logged from the same line each time revises itself instead of piling up.

for batch in cg.logging.progress(batches, label="Training"):
    loss = train(batch)
    cg.logging.info(f"loss {loss:.3f}", loss=loss)

Parameters:

Name Type Description Default
iterable Iterable[T] | None

What to iterate; None for a count advanced by hand.

None
total int | None

How many units there are; the iterable's length when it has one.

None
label str | None

What the count shows; progress when unnamed.

None
key str | None

A slot of your own; see info.

None
Source code in capturegraph-lib/capturegraph/logging/scope.py
def progress[T](
    iterable: Iterable[T] | None = None,
    *,
    total: int | None = None,
    label: str | None = None,
    key: str | None = None,
) -> Progress[T]:
    """A counted entry: iterate it, or hold it and ``advance`` it.

    Iterating numbers the iterations, and inside the loop an entry logged from
    the same line each time revises itself instead of piling up.

    ```python
    for batch in cg.logging.progress(batches, label="Training"):
        loss = train(batch)
        cg.logging.info(f"loss {loss:.3f}", loss=loss)
    ```

    Args:
        iterable: What to iterate; ``None`` for a count advanced by hand.
        total: How many units there are; the iterable's length when it has one.
        label: What the count shows; ``progress`` when unnamed.
        key: A slot of your own; see ``info``.
    """
    if total is None and isinstance(iterable, Sized):
        total = len(iterable)
    scope = listening()
    if scope is None:
        return Progress(None, "", None, "", {}, None, total=total, iterable=iterable)
    parent, log = scope
    return log.add_progress(
        parent,
        label if label is not None else "progress",
        key=key,
        site=_site(),
        total=total,
        iterable=iterable,
    )

to(*sinks) #

Route everything logged in the block to sinks.

with cg.logging.to(cg.logging.Terminal()) as log:
    thumbnails = journal.sessions.photo.pmap(session_thumbnail)
print(len(log.entries()), "entries")

Parameters:

Name Type Description Default
sinks Sink

Where the entries go; none collects them in the returned log only.

()

Yields:

Type Description
Log

The log being written.

Source code in capturegraph-lib/capturegraph/logging/scope.py
@contextmanager
def to(*sinks: Sink) -> Iterator[Log]:
    """Route everything logged in the block to ``sinks``.

    ```python
    with cg.logging.to(cg.logging.Terminal()) as log:
        thumbnails = journal.sessions.photo.pmap(session_thumbnail)
    print(len(log.entries()), "entries")
    ```

    Args:
        sinks: Where the entries go; none collects them in the returned log only.

    Yields:
        The log being written.
    """
    log = Log(sinks)
    for sink in sinks:
        sink.start(log)
    token = ambient.set(log.root)
    try:
        yield log
    finally:
        ambient.reset(token)
        for sink in sinks:
            sink.finish()

warning(message, *, key=None, kind='text', **fields) #

Log message at warning; see info.

Source code in capturegraph-lib/capturegraph/logging/scope.py
def warning(
    message: str,
    *,
    key: str | None = None,
    kind: Kind = "text",
    **fields: JSONValue,
) -> Entry:
    """Log ``message`` at ``warning``; see ``info``."""
    return _add("warning", message, fields, key, kind, _site())