Skip to content

entry

entry #

Entry — one line of a log, and Progress, one that counts.

  1. A line. info("…") makes an entry complete as it stands: a level, a message, named fields, and when it happened. Its kind says what the message is, so a renderer can show it as such: prose, a shell command, or a program's output (which may carry ANSI colour codes).
  2. A scope. with on an entry makes it the ambient parent for the block: entries made inside sit beneath it, and it ends done, or failed with the exception's text.
  3. A count. Progress adds done/total: iterating it runs each element as a turn — numbered, ambient for its block, counted when it ends — and advance and update(done=…) count from any thread that holds it.

Every change goes through the entry's Log, which bumps revision and tells the sinks. An entry with no log — what the verbs return when nothing is listening — accepts every call and records nothing.

INERT = Entry(None, '', None, 'info', '', {}, None) module-attribute #

What the verbs return when nothing is listening: it accepts every call and records nothing.

ambient = ContextVar('cg_logging_ambient', default=None) module-attribute #

The entry new entries sit beneath; None when nothing is listening.

Entry #

One line of a log; with makes it a scope.

Attributes:

Name Type Description
id

Unique within its log; "" for an entry that records nothing.

parent

The id of the entry this one sits beneath, None at the top.

level

info, warning or error.

message

What the line says.

kind Kind

What the message is: text, a shell command, or a program's output.

fields

Named values the line carries.

done int | None

How many units are done, for a Progress.

total int | None

How many there are, for a Progress that knows.

iteration int | None

The enclosing loop's iteration when the entry was last logged.

started

When the entry was made, as time.time().

ended float | None

When the scope ended, or started for a plain line; None while open.

status Status

open inside its with block, else done or failed.

error str | None

The exception text of a failed scope: its type and message, then each of its notes on a line of its own.

revision

How many times the entry has changed since it was made.

Source code in capturegraph-lib/capturegraph/logging/entry.py
class Entry:
    """One line of a log; ``with`` makes it a scope.

    Attributes:
        id: Unique within its log; ``""`` for an entry that records nothing.
        parent: The id of the entry this one sits beneath, ``None`` at the top.
        level: ``info``, ``warning`` or ``error``.
        message: What the line says.
        kind: What the message is: ``text``, a shell ``command``, or a
            program's ``output``.
        fields: Named values the line carries.
        done: How many units are done, for a ``Progress``.
        total: How many there are, for a ``Progress`` that knows.
        iteration: The enclosing loop's iteration when the entry was last logged.
        started: When the entry was made, as ``time.time()``.
        ended: When the scope ended, or ``started`` for a plain line; ``None`` while open.
        status: ``open`` inside its ``with`` block, else ``done`` or ``failed``.
        error: The exception text of a failed scope: its type and message, then
            each of its notes on a line of its own.
        revision: How many times the entry has changed since it was made.
    """

    __slots__ = (
        "_log",
        "_token",
        "done",
        "ended",
        "error",
        "fields",
        "id",
        "iteration",
        "kind",
        "level",
        "message",
        "parent",
        "revision",
        "started",
        "status",
        "total",
    )

    def __init__(
        self,
        log: Log | None,
        id: str,
        parent: str | None,
        level: Level,
        message: str,
        fields: dict[str, JSONValue],
        iteration: int | None,
        kind: Kind = "text",
    ) -> None:
        """An entry of ``log`` beneath ``parent``; the verbs make these, not callers."""
        self._log = log
        self.id = id
        self.parent = parent
        self.level = level
        self.message = message
        self.kind: Kind = kind
        self.fields = fields
        self.done: int | None = None
        self.total: int | None = None
        self.iteration: int | None = iteration
        self.started = time.time()
        self.ended: float | None = self.started
        self.status: Status = "done"
        self.error: str | None = None
        self.revision = 0
        self._token: Token[Entry | None] | None = None

    def update(
        self,
        message: str | None = None,
        *,
        done: int | None = None,
        **fields: JSONValue,
    ) -> None:
        """Change the message, the count and the named fields in one revision."""
        if self._log is None:
            return
        with self._log.changing(self):
            if message is not None:
                self.message = message
            if done is not None:
                self.done = done
            self.fields.update(fields)

    def __enter__(self) -> Self:
        """Open the scope: entries logged in the block sit beneath this one."""
        if self._log is None:
            return self
        self._token = ambient.set(self)
        with self._log.changing(self):
            self.status = "open"
            self.ended = None
        return self

    def __exit__(
        self,
        kind: type[BaseException] | None,
        error: BaseException | None,
        traceback: TracebackType | None,
    ) -> None:
        """Close the scope as ``done``, or ``failed`` carrying the exception's text."""
        if self._log is None:
            return
        if self._token is not None:
            ambient.reset(self._token)
            self._token = None
        with self._log.changing(self):
            self.ended = time.time()
            self.status = "done" if error is None else "failed"
            self.error = describe(error) if error is not None else None

    def json(self) -> dict[str, JSONValue]:
        """The entry as the wire shape every renderer reads."""
        return {
            "id": self.id,
            "parent": self.parent,
            "level": self.level,
            "message": self.message,
            "kind": self.kind,
            "fields": dict(self.fields),
            "done": self.done,
            "total": self.total,
            "iteration": self.iteration,
            "started": self.started,
            "ended": self.ended,
            "status": self.status,
            "error": self.error,
            "revision": self.revision,
        }

    @property
    def elapsed(self) -> float:
        """Seconds the entry has been open, or was open for."""
        return (self.ended if self.ended is not None else time.time()) - self.started

    def __repr__(self) -> str:
        """``Entry(<level>, <message>)``."""
        return f"{type(self).__name__}({self.level!r}, {self.message!r})"

elapsed property #

Seconds the entry has been open, or was open for.

__enter__() #

Open the scope: entries logged in the block sit beneath this one.

Source code in capturegraph-lib/capturegraph/logging/entry.py
def __enter__(self) -> Self:
    """Open the scope: entries logged in the block sit beneath this one."""
    if self._log is None:
        return self
    self._token = ambient.set(self)
    with self._log.changing(self):
        self.status = "open"
        self.ended = None
    return self

__exit__(kind, error, traceback) #

Close the scope as done, or failed carrying the exception's text.

Source code in capturegraph-lib/capturegraph/logging/entry.py
def __exit__(
    self,
    kind: type[BaseException] | None,
    error: BaseException | None,
    traceback: TracebackType | None,
) -> None:
    """Close the scope as ``done``, or ``failed`` carrying the exception's text."""
    if self._log is None:
        return
    if self._token is not None:
        ambient.reset(self._token)
        self._token = None
    with self._log.changing(self):
        self.ended = time.time()
        self.status = "done" if error is None else "failed"
        self.error = describe(error) if error is not None else None

__init__(log, id, parent, level, message, fields, iteration, kind='text') #

An entry of log beneath parent; the verbs make these, not callers.

Source code in capturegraph-lib/capturegraph/logging/entry.py
def __init__(
    self,
    log: Log | None,
    id: str,
    parent: str | None,
    level: Level,
    message: str,
    fields: dict[str, JSONValue],
    iteration: int | None,
    kind: Kind = "text",
) -> None:
    """An entry of ``log`` beneath ``parent``; the verbs make these, not callers."""
    self._log = log
    self.id = id
    self.parent = parent
    self.level = level
    self.message = message
    self.kind: Kind = kind
    self.fields = fields
    self.done: int | None = None
    self.total: int | None = None
    self.iteration: int | None = iteration
    self.started = time.time()
    self.ended: float | None = self.started
    self.status: Status = "done"
    self.error: str | None = None
    self.revision = 0
    self._token: Token[Entry | None] | None = None

__repr__() #

Entry(<level>, <message>).

Source code in capturegraph-lib/capturegraph/logging/entry.py
def __repr__(self) -> str:
    """``Entry(<level>, <message>)``."""
    return f"{type(self).__name__}({self.level!r}, {self.message!r})"

json() #

The entry as the wire shape every renderer reads.

Source code in capturegraph-lib/capturegraph/logging/entry.py
def json(self) -> dict[str, JSONValue]:
    """The entry as the wire shape every renderer reads."""
    return {
        "id": self.id,
        "parent": self.parent,
        "level": self.level,
        "message": self.message,
        "kind": self.kind,
        "fields": dict(self.fields),
        "done": self.done,
        "total": self.total,
        "iteration": self.iteration,
        "started": self.started,
        "ended": self.ended,
        "status": self.status,
        "error": self.error,
        "revision": self.revision,
    }

update(message=None, *, done=None, **fields) #

Change the message, the count and the named fields in one revision.

Source code in capturegraph-lib/capturegraph/logging/entry.py
def update(
    self,
    message: str | None = None,
    *,
    done: int | None = None,
    **fields: JSONValue,
) -> None:
    """Change the message, the count and the named fields in one revision."""
    if self._log is None:
        return
    with self._log.changing(self):
        if message is not None:
            self.message = message
        if done is not None:
            self.done = done
        self.fields.update(fields)

Progress #

Bases: Entry

An entry that counts; iterate it, or advance/update it by hand.

for batch in cg.logging.progress(batches, label="Training"):
    ...

with cg.logging.progress(total=len(jobs), label="Rendering") as bar:
    for job in jobs:
        render(job)
        bar.advance()
Source code in capturegraph-lib/capturegraph/logging/entry.py
class Progress[T](Entry):
    """An entry that counts; iterate it, or ``advance``/``update`` it by hand.

    ```python
    for batch in cg.logging.progress(batches, label="Training"):
        ...

    with cg.logging.progress(total=len(jobs), label="Rendering") as bar:
        for job in jobs:
            render(job)
            bar.advance()
    ```
    """

    __slots__ = ("_iterable",)

    def __init__(
        self,
        log: Log | None,
        id: str,
        parent: str | None,
        message: str,
        fields: dict[str, JSONValue],
        iteration: int | None,
        *,
        total: int | None,
        iterable: Iterable[T] | None,
    ) -> None:
        """A count of ``total`` beneath ``parent``, over ``iterable`` when given."""
        super().__init__(log, id, parent, "info", message, fields, iteration)
        self.done = 0
        self.total = total
        self._iterable = iterable

    def __iter__(self) -> Iterator[T]:
        """The elements, each an iteration this entry is the ambient parent of.

        Raises:
            TypeError: If the progress was made without an iterable.
        """
        if self._iterable is None:
            raise TypeError(
                "this progress has nothing to iterate; pass an iterable or advance() it"
            )
        if self._log is None:
            yield from self._iterable
            return
        with self._log.changing(self):
            self.status = "open"
            self.ended = None
        try:
            for item in self._iterable:
                with self.turn():
                    yield item
        finally:
            if self._token is None:
                with self._log.changing(self):
                    self.status = "done"
                    self.ended = time.time()

    @contextmanager
    def turn(self) -> Iterator[None]:
        """One iteration as a block: numbered, the ambient parent inside, counted on its way out.

        A block that raises or is broken out of is not counted. Iterating does
        this per element; call it yourself when the elements come to you one
        at a time, as a ``pmap`` worker's do.

        ```python
        with worker.turn():
            render(frame)
        ```
        """
        if self._log is None:
            yield
            return
        with self._log.changing(self):
            self.iteration = 0 if self.iteration is None else self.iteration + 1
        token = ambient.set(self)
        try:
            yield
        finally:
            ambient.reset(token)
        self.advance()

    def advance(self, count: int = 1) -> None:
        """Count ``count`` more units done."""
        if self._log is None:
            return
        with self._log.changing(self):
            self.done = (self.done or 0) + count

__init__(log, id, parent, message, fields, iteration, *, total, iterable) #

A count of total beneath parent, over iterable when given.

Source code in capturegraph-lib/capturegraph/logging/entry.py
def __init__(
    self,
    log: Log | None,
    id: str,
    parent: str | None,
    message: str,
    fields: dict[str, JSONValue],
    iteration: int | None,
    *,
    total: int | None,
    iterable: Iterable[T] | None,
) -> None:
    """A count of ``total`` beneath ``parent``, over ``iterable`` when given."""
    super().__init__(log, id, parent, "info", message, fields, iteration)
    self.done = 0
    self.total = total
    self._iterable = iterable

__iter__() #

The elements, each an iteration this entry is the ambient parent of.

Raises:

Type Description
TypeError

If the progress was made without an iterable.

Source code in capturegraph-lib/capturegraph/logging/entry.py
def __iter__(self) -> Iterator[T]:
    """The elements, each an iteration this entry is the ambient parent of.

    Raises:
        TypeError: If the progress was made without an iterable.
    """
    if self._iterable is None:
        raise TypeError(
            "this progress has nothing to iterate; pass an iterable or advance() it"
        )
    if self._log is None:
        yield from self._iterable
        return
    with self._log.changing(self):
        self.status = "open"
        self.ended = None
    try:
        for item in self._iterable:
            with self.turn():
                yield item
    finally:
        if self._token is None:
            with self._log.changing(self):
                self.status = "done"
                self.ended = time.time()

advance(count=1) #

Count count more units done.

Source code in capturegraph-lib/capturegraph/logging/entry.py
def advance(self, count: int = 1) -> None:
    """Count ``count`` more units done."""
    if self._log is None:
        return
    with self._log.changing(self):
        self.done = (self.done or 0) + count

turn() #

One iteration as a block: numbered, the ambient parent inside, counted on its way out.

A block that raises or is broken out of is not counted. Iterating does this per element; call it yourself when the elements come to you one at a time, as a pmap worker's do.

with worker.turn():
    render(frame)
Source code in capturegraph-lib/capturegraph/logging/entry.py
@contextmanager
def turn(self) -> Iterator[None]:
    """One iteration as a block: numbered, the ambient parent inside, counted on its way out.

    A block that raises or is broken out of is not counted. Iterating does
    this per element; call it yourself when the elements come to you one
    at a time, as a ``pmap`` worker's do.

    ```python
    with worker.turn():
        render(frame)
    ```
    """
    if self._log is None:
        yield
        return
    with self._log.changing(self):
        self.iteration = 0 if self.iteration is None else self.iteration + 1
    token = ambient.set(self)
    try:
        yield
    finally:
        ambient.reset(token)
    self.advance()

describe(error) #

Type: message, then each note the exception carries on its own line.

Source code in capturegraph-lib/capturegraph/logging/entry.py
def describe(error: BaseException) -> str:
    """``Type: message``, then each note the exception carries on its own line."""
    notes: list[str] = getattr(error, "__notes__", [])
    return "\n".join([f"{type(error).__name__}: {error}", *notes])

listening() #

The ambient parent and the log it belongs to, or None when nothing is listening.

Source code in capturegraph-lib/capturegraph/logging/entry.py
def listening() -> tuple[Entry, Log] | None:
    """The ambient parent and the log it belongs to, or ``None`` when nothing is listening."""
    parent = ambient.get()
    if parent is None or parent._log is None:
        return None
    return parent, parent._log