Skip to main content

alis-build-alog

Structured logging for services on the Alis Build platform.

Cloud Logging's agents read a container's stdout and stderr and parse each line. A line that happens to be a JSON object with the right keys becomes a structured entry — severity, a link to its trace, labels, request metadata — and a line that is not becomes flat text with none of that. This package makes sure the lines are the first kind, and prints something readable instead when you are running locally.

Nothing here calls the Logging API. The package only decides what a line looks like; the platform does the ingesting.

pip install alis-build-alog

The core has no dependencies.

Install Adds Pulls in
alis-build-alog Formatters, levels, binding, ASGI middleware, test helpers nothing
alis-build-alog[grpc] gRPC server interceptors grpcio

Importing a subpackage without its extra tells you exactly what to install.

Status: early development. The public API is not yet stable.

Getting going

Call configure() once at startup and everything that logs through the standard library comes out in the right format — your own loggers and every library you depend on alike.

import logging
from alis.build import alog

alog.configure()

logging.getLogger(__name__).info("server started")
alog.info("or use the shortcut, which does the same thing")

There are shortcuts for each severity: debug, info, notice, warning, error, critical, alert, emergency, plus exception and fatal. They work without configure() too, so a script does not need any setup. Pass arguments rather than building an f-string — for a line the level discards, the interpolation never has to happen:

alog.info("processed %s in %dms", key, elapsed)

Importing the package changes no logging state. A library that installs handlers on import fights dictConfig, a server's own setup and a test runner's capture, and makes import order matter, so configure() is the explicit opt-in.

Cloud and local output

configure() picks the format from the environment. K_SERVICE, CLOUD_RUN_JOB or KUBERNETES_SERVICE_HOST means a runtime is collecting and parsing stdout, so it writes JSON; anything else is taken to be a terminal, so it writes coloured text. ALOG_MODE=cloud|local overrides it.

{"message":"server started","severity":"NOTICE","logging.googleapis.com/trace":"projects/p/traces/abc","time":"2025-08-26T12:00:00.123456Z","logging.googleapis.com/spanId":"456"}

The local layout is not a contract — it exists to be read by a person and is free to change whenever a change makes it easier to read. Do not parse it; parse the JSON. Colour turns off when the stream is not a terminal, when NO_COLOR is set to anything, or when TERM=dumb; ALOG_COLOR=always|never forces it either way.

Severity levels

Cloud Logging recognises nine severities; the standard library ships five. The three missing ones are registered as real levels, so ordinary comparisons and setLevel keep working:

NOTSET DEBUG INFO NOTICE WARNING ERROR CRITICAL ALERT EMERGENCY
0 10 20 25 30 40 50 60 70

Severity is derived from whatever number a record carries, so a library logging at plain INFO is reported as INFO without knowing this package exists. A level between two of them takes the severity below it, and anything under DEBUG becomes DEFAULT.

The minimum level defaults to DEBUG locally and INFO in the cloud — locally the detail is the point, in production the volume is the problem. ALOG_LEVEL overrides it with a level name in any casing or a number, and raises on anything else rather than falling back: a service that silently logs at the wrong level looks healthy right up until the incident where its debug lines were needed.

Binding metadata to a request

Everything a log line carries beyond its message is ambient, bound to the context rather than passed down through every call. A logging call deep in a handler still lands with the request's trace on it.

with alog.bind(labels={"route": "/v1/users"}, request_id="r-7"):
    alog.info("handling")  # carries both

Nesting merges the mapping-shaped arguments — labels and arbitrary fields — and replaces the rest. On a key collision the inner value wins. Anything that is not a name the format defines becomes a field on the line itself; extra= on an ordinary logging call does the same.

bind also takes operation, insert_id and http_request, which fill in the corresponding parts of the structured entry.

Two behaviours worth knowing before you rely on this: a task created with create_task inherits the binding and cannot leak its own changes back to its parent, but a plain thread starts with nothing bound. Where a framework hands you separate enter and exit callbacks rather than a block, drive bind with contextlib.ExitStack.

Trace correlation

Correlating logs with their trace is what lets Logs Explorer show a request's lines against its trace. The header comes in on the request; bind it at the transport boundary and every line written while handling that request picks it up.

Over HTTP

from alis.build.alog.asgi import TraceContextMiddleware

app = TraceContextMiddleware(app)

Pure ASGI3 with no framework import, so it works under Starlette, FastAPI, Litestar, Quart and async Django alike.

Over gRPC

from alis.build.alog.grpc import AsyncTraceContextInterceptor

server = grpc.aio.server(interceptors=[AsyncTraceContextInterceptor()])

TraceContextInterceptor is the synchronous equivalent. Both keep the binding open across a streaming response, not merely while the generator is created.

The trace resource name needs a project, taken from the first non-empty of ALIS_OS_PROJECT, GOOGLE_CLOUD_PROJECT or GCLOUD_PROJECT. Without one there is nothing to correlate against, so the trace keys are left off rather than written half-formed.

Errors

try:
    ...
except ValueError:
    alog.exception("handler failed")

The traceback lands on stack_trace, which is the key Error Reporting groups by — an exception logged any other way is one that never gets counted.

alog.fatal(...) writes a critical line and then raises SystemExit(1) rather than exiting outright, so finally blocks, context managers and atexit handlers still run.

Testing

from alis.build.alog.testing import capture, fresh_logging_config


def test_it_logs_the_route():
    with capture() as captured:
        handle_request()

    assert captured.entries[0]["logging.googleapis.com/labels"] == {"route": "/v1"}

capture() collects the formatted lines instead of printing them, so a test can assert on the line rather than only on the message. fresh_logging_config() puts process-wide logging configuration back the way it was; use it as an autouse fixture, since a test that reconfigures logging without restoring it changes the result of every test that runs afterwards.

License

Apache-2.0

Metadata

Release files for alis-build-alog 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for alis-build-alog 0.1.0
File Size Uploaded Provenance Actions
alis_build_alog-0.1.0.tar.gz 41.5 kB With provenance Details for alis_build_alog-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for alis-build-alog 0.1.0
File Interpreter ABI Platform Actions
alis_build_alog-0.1.0-py3-none-any.whl Python 3 none any Details for alis_build_alog-0.1.0-py3-none-any.whl

Total release size: 77.9 kB

Release files / alis_build_alog-0.1.0.tar.gz

Download URL alis_build_alog-0.1.0.tar.gz
Size 41.5 kB
Tags Source
SHA-256 checksum
How to use checksums
382ee2eb12e095e76e635dd8afe1a5f8de01cc0cbe69e10b8c532d861d4bde20
BLAKE2b-256 checksum
How to use checksums
8bdc49635545b91548f15def59655952f1480bf8b9d3d9225b7722b13e3af594
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 30, 2026.

Transparency log

Release files / alis_build_alog-0.1.0-py3-none-any.whl

Download URL alis_build_alog-0.1.0-py3-none-any.whl
Size 36.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2ad11c2cc71ef1b046511431c7d021c07a2ea18e16234504c024fc4b6b748664
BLAKE2b-256 checksum
How to use checksums
cd4fc2e7730481bb20c7090e63108e7a2d16f4617155394f37b8fe72f3ef8855
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 30, 2026.

Transparency log

Security for alis-build-alog 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for alis_build_alog-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 30, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page