Skip to main content

tracing-logger

High-performance Python logging framework · bounded queue · rotation · compression · async · metrics

Python >= 3.12 License: MIT Platform Version 0.1.1 abi3-py312

简体中文 · English

Python logging usually formats and writes to handlers on caller threads, so a slow handler directly slows every caller. tracing-logger moves records to a bounded queue and a dedicated writer; file I/O, rotation, compression, and metrics run in the background.

The hot path is an abi3 native extension with familiar calls: LoggerConfig, getLogger, info/exception, async a*, catch/acatch, and Prometheus metrics. On one thread, direct calls sustain about 1.0–1.2M records/s and internal batching with fmt="%(message)s" reaches about 2.1–2.3M records/s; caller threads only format and enqueue, without opening files or taking a global lock.

✨ Features

  • One entry point: basicConfig, getLogger, and setup_logging, plus debug / info / warning / error / critical / exception. Levels can be names or numbers.
  • Producers never touch disk: log.info() filters the level, captures the caller, formats % arguments, and enqueues. Each logger gets a bounded queue and a writer thread by default.
  • Bounded queues: queue_size limits records, max_queued_bytes limits estimated bytes. overflow="drop" drops new records and counts them; overflow="block" applies backpressure. rate_limit caps records per second.
  • Internal batching: the public API stays log.info / log.warning / log.error. log_batch=True is just a keyword argument on log.info, off by default. There is no separate batch API.
  • Rotation and compression: rotate by time (S/M/H/D/MIDNIGHT/W*) or size. gzip, zstd, and lz4 compress archives on a background thread.
  • Async: ainfo, aflush, asetup_logging, and ashutdown. With overflow="block", potentially blocking enqueues run in asyncio.to_thread and do not stall the event loop.
  • JSON and tracebacks: json=True emits JSON Lines. exception() attaches the current traceback, and both console and file output keep physical newlines.
  • Observability and safety: health(), Prometheus text, JSON snapshots, an instance lock, per-process file isolation, Unix 0600, and O_NOFOLLOW by default. The package has no network client or telemetry.

🚀 Quick Start

Requirements

  • Python 3.12+. Wheels use abi3-py312, so one platform wheel covers CPython 3.12, 3.13, and 3.14.
  • Windows x64, Linux x86_64, and Linux aarch64 (manylinux_2_28).
  • Running a wheel does not require a compiler or extra Python packages. Compression codecs are built into the extension.
  • Only non-UTF-8 encodings or Python fallback sinks with a custom Rotation need zstandard / lz4 for compression. gzip is built in.

Install

Choose the abi3 wheel that matches the platform from GitHub Releases:

# Windows x64
pip install tracing_logger-0.1.1-cp312-abi3-win_amd64.whl

# Linux x86_64
pip install tracing_logger-0.1.1-cp312-abi3-manylinux_2_28_x86_64.whl

# Linux aarch64
pip install tracing_logger-0.1.1-cp312-abi3-manylinux_2_28_aarch64.whl

Minimal example

basicConfig and getLogger are the primary entry points. getLogger is an alias for get_logger; basicConfig and setup_logging share the same configuration and registry.

from tracing_logger import LoggerConfig, basicConfig, getLogger, flush, shutdown

basicConfig(
    LoggerConfig(
        base_path="logs",
        name="billing",
        level="INFO",
        when="D",          # daily rotation; None disables time-based rotation
        keep=7,
        console=True,
        compression="zstd",
    )
)

log = getLogger("billing")
log.info("order %s created", "A-1001")
log.warning("downstream latency=%dms", 350)

try:
    1 / 0
except ZeroDivisionError:
    log.exception("payment failed")  # includes the current traceback

flush()        # drain the queue and flush every sink
shutdown()     # stop all loggers; atexit also calls it; idempotent

Default output:

logs/billing.log        # < ERROR
logs/billing_error.log  # >= ERROR

With the default logger name runlog, the error file is error.log. Files open lazily: creating a config or logger does not touch disk. Directories and files are created on the first write.

Everyday calls

Use log.info / log.warning / log.error / log(...) directly. There is no need to change call sites for throughput:

log.info("order %s created", order_id)
log.warning("queue depth=%d", depth)

try:
    charge(order)
except PaymentError:
    log.error("charge failed")      # includes the traceback inside except

log.log("INFO", "custom level")     # level name or number
log.log(30, "warning by number")
  • Regular services: setup_logging(LoggerConfig.for_service("api")), then get_logger("api"). This uses native file sinks, daily rotation, and an instance lock.
  • High throughput: keep log.info and pass log_batch=True. Use a simple template such as "%(message)s" for pure throughput and keep detailed templates for debugging and audit logs.
  • Async services: await asetup_logging(...), call await log.ainfo(...) in request paths, and await ashutdown() on exit.
  • Startup warm-up: call preload(("api", "worker")) at startup so the first requests do not pay runtime and writer initialization costs.
  • Audit logs: use LoggerConfig.durable(...), or enable sync_on_flush / sync_each_batch, and monitor health()["drop_reasons"].

📚 Guide

Configuration: LoggerConfig

LoggerConfig is a frozen=True, slots=True dataclass. It validates every field at construction time and raises ValueError for invalid values. To change a few fields, use config.override(...) and keep the original object unchanged.

Common fields:

Field Default Purpose
base_path / name "logs" / "runlog" Log root and logger name
name_as_folder False Use the logger name as a subdirectory; for_service() enables it
level "INFO" Level name or number
fmt / date_fmt DEFAULT_FORMAT / "%Y-%m-%d %H:%M:%S" Line template and time format
console / files False / True Write to stderr / create log files
queue_size / max_queued_bytes 65_536 / None Record and estimated-byte budgets
overflow / rate_limit "drop" / None Drop or backpressure; per-second limit
flush_each / file_buffer_size True / 64 KiB Flush per batch and file buffer size
sync_on_flush / sync_each_batch False / False fsync on explicit flush / on every batch
when / interval / keep "D" / 1 / 3 Time rotation and archive retention
max_bytes None Per-file size limit
compression None "gzip" / "zstd" / "lz4"
producer_batch_size / producer_flush_interval_ms 512 / 1.0 Internal batch thresholds
isolate_python_sinks False Separate file and Python sink writers
proc_split / instance_lock 0 / False Per-process files / single-instance lock
json / sinks False / () JSON Lines / extra sinks
traceback / auto_exc_info True / True Traceback on exception() / auto traceback on error
follow_symlinks False Allow log paths to follow symbolic links

Path helpers only compute paths; they do not touch the filesystem:

config = LoggerConfig(base_path="/var/log/app", name="billing")
config.log_dir()          # /var/log/app
config.file_path()        # /var/log/app/billing.log
config.error_file_path()  # /var/log/app/billing_error.log
config.lock_path()        # /var/log/app/billing.log.lock

With name_as_folder=True, the layout becomes <base>/<name>/<name>.log; error files, lock files, and rotated archives stay in that directory. With proc_split=1/2, file names include the process name or pid, for example billing_2048.log and billing_2048_error.log.

Project layouts can use for_project or production:

config = LoggerConfig.for_project("api", project_root="/srv/app")
config.file_path()  # /srv/app/output/logs/api/api.log

production = LoggerConfig.production("api", project_root="/srv/app")
# JSON Lines + service directory + high-volume file sink

Lifecycle and warm-up

from tracing_logger import LoggerConfig, get_logger, get_service_logger
from tracing_logger import setup_logging, flush, shutdown, dropped

setup_logging(LoggerConfig.for_service("api", base_path="/var/log/app"))
log = get_logger("api")
log.info("service ready")

billing = get_service_logger("billing")
flush()                    # queue barrier; does not stop writers
ok = shutdown()            # reject new records -> drain -> flush/close -> join threads
  • setup_logging is idempotent. Use setup_logging(config, force=True) to replace the configuration. During a rebuild, get_logger() returns a facade that only counts drops.
  • get_logger(name) returns the same native facade for the same name. Passing a different configuration after assembly does not rebuild it.
  • preload(("api", "worker")) assembles several loggers at startup in one call.
  • flush() is a queue barrier. shutdown() is idempotent, and atexit calls it automatically. Both return bool.
  • After shutdown(), get_logger() returns a dropping facade. Call setup_logging(...) explicitly to restore logging.
  • dropped() returns the process-wide drop count. log.dropped and health()["dropped"] use the same counter.
  • After fork, call setup_logging in the child. Do not reuse the parent runtime. Windows has no fork.

Formatting and tracebacks

log.info("order %s amount=%d", order_id, amount)
log.error("failed")                  # includes traceback inside except
log.error("failed", exc_info=False)  # disable auto traceback for this call
log.exception("failed")              # explicitly attach the current traceback

log.level = "DEBUG"                  # equivalent to set_level("DEBUG")
if log.isEnabledFor(10):             # check before building expensive messages
    log.debug("payload=%r", payload)
  • msg can be any object: it is converted with str(msg), then Python % formatting runs if args are present.
  • args are formatted at emit time on the caller thread, so strings are not built early.
  • exc_info accepts True, an exception object, a tuple, False, or None.
  • exception() attaches a traceback by default; traceback=False disables it. Auto traceback for error / critical inside except is controlled by auto_exc_info.
  • Formatting failures never propagate to application code. They are counted under the format drop reason and reported once.

Default line format:

[2026-10-30 12:00:00-123] [pid:thread] [pkg::module::123::INFO] > message

Internal batching

The public API has no batch methods. Batching is internal and enabled per call with log_batch=True (default False):

setup_logging(
    LoggerConfig(
        base_path="logs",
        name="ingest",
        when=None,
        queue_size=1_000_000,
        producer_batch_size=512,
        producer_flush_interval_ms=1.0,
        flush_each=False,
        file_buffer_size=1 << 20,
    )
)
log = get_logger("ingest")

for index in range(1_000_000):
    log.info("record %d", index, log_batch=True)
log.flush()
  • Records enter a thread-local buffer first. A batch is enqueued when producer_batch_size is reached or producer_flush_interval_ms elapses.
  • The writer merges up to 4096 records or 4 MiB before writing to a sink, reducing channel, lock, and syscall overhead.
  • Enqueue releases the GIL. If a thread mixes direct calls with batching, the buffer is drained before the direct call so ordering is preserved.
  • Batching supports overflow="drop" only. Direct calls are required for strict backpressure.

For counting only, use NullSink:

from tracing_logger import LoggerConfig, NullSink, get_logger, setup_logging

setup_logging(
    LoggerConfig(
        base_path="logs",
        name="metrics-only",
        files=False,
        when=None,
        sinks=(NullSink(),),
    )
)
log = get_logger("metrics-only")
log.info("counted only")

Async

import asyncio
import tracing_logger as sl

async def main():
    await sl.asetup_logging(sl.LoggerConfig.for_service("web"))
    log = await sl.aget_logger("web")
    await log.ainfo("request %s", "id-1")
    await log.aerror("upstream failed")
    await log.aflush()
    await sl.ashutdown()

asyncio.run(main())
  • Async methods return awaitables. Without await, nothing is written and no record is constructed.
  • The caller location and exc_info are captured at call time; rendering happens at await time.
  • With overflow="drop", enqueue is non-blocking. With overflow="block", a full queue moves the enqueue to asyncio.to_thread, keeping the event loop responsive.
  • FastAPI and aiohttp can call await log.ainfo(...) directly; run_in_executor is unnecessary.
  • Do not call aflush / flush / shutdown inside a custom Sink; those control calls wait for the writer.

Rotation and compression

LoggerConfig(
    base_path="/var/log/app",
    name="billing",
    when="D",             # S/M/H/D/MIDNIGHT/W0..W6
    interval=1,
    keep=7,
    max_bytes=64 << 20,   # with time rotation, whichever comes first wins
    compression="zstd",   # "gzip" / "zstd" / "lz4"
)
Mode Archive name Ordering
Size billing.log.1, billing.log.2, … .1 is newest
S / M / H billing.log.2026-10-31_12-00-05, … interval start time
D / MIDNIGHT / W* billing.log.2026-10-31 date
  • when accepts S, M, H, D, MIDNIGHT, and W0…W6, case-insensitively. MIDNIGHT / W* only support interval=1.
  • Existing files use their mtime to resume the next boundary; a restart does not reset the schedule to “from now”.
  • Compression runs on a background thread after rotation with bounded memory. On failure, the plain archive is kept and a warning is recorded.
  • Time-only rotation does not wait for background compression. Size rotation, flush(), and close() do.
  • keep counts archive generations; compressed suffixes do not consume extra slots.

JSON and custom sinks

LoggerConfig(
    base_path="logs",
    name="api",
    json=True,   # JSON Lines; fmt is ignored
)

JSON fields include schema/time/level/logger/pid/thread/message, with optional file/line/module_chain/exception. json=True cannot be combined with color options. Text templates support asctime, msecs, process, thread, module_chain, lineno, levelname, message, and other fields. Unknown fields or conversions raise ValueError during assembly.

A custom sink needs matches / write / flush / close. Implementing the optional block protocol lets the writer merge records of the same level into one multi-line string:

from tracing_logger import Handler, LoggerConfig, get_logger, setup_logging

class MemorySink:
    matches_all_levels = True  # skip per-record Python matches calls

    def __init__(self):
        self.lines = []

    def matches(self, level_no):
        return True

    def write(self, text):
        self.lines.append(text)

    def write_many(self, texts):
        self.lines.extend(texts)

    def write_block(self, level_no, block):
        self.lines.extend(block.splitlines())

    def flush(self):
        pass

    def close(self):
        pass

    def discard_after_fork(self):
        self.lines.clear()

memory = MemorySink()
setup_logging(
    LoggerConfig(
        base_path="logs",
        name="memory",
        files=False,
        sinks=(Handler("memory", memory),),
    )
)
get_logger("memory").info("hello")
  • write_many is optional. Without it, records are written one by one.
  • write_block is optional. When implemented, each batch costs one Python call instead of one per record.
  • matches_all_levels = True suits sinks that accept every level. Do not set it when the sink filters records.
  • write / flush / close run only on the writer thread; the sink does not need its own lock.
  • Slow Python sinks can set isolate_python_sinks=True to run file sinks and Python sinks on separate writer threads. Ordering is preserved within a group, not across groups.

Exception handling

from tracing_logger import acatch, catch

@catch(log=log, default=None)
def load_config(path):
    ...

@catch(log=log, handler=lambda exc, lg: "fallback")
def guarded():
    ...

@acatch(log=log, reraise=True)
async def fetch(url):
    ...

Only Exception is caught. default is the return value when no custom handler is given; reraise=True logs the exception and re-raises it. A synchronous catch handler must not return an awaitable; use acatch in async code.

Health and metrics

health = log.health()
print(health["pending"], health["dropped"], health["drop_reasons"])

from tracing_logger import prometheus, snapshot

text = prometheus()   # Prometheus text, ready for /metrics
data = snapshot()     # {"dropped_total": int, "loggers": [health, ...]}

Common fields:

Key Meaning
alive Whether all writers are alive
pending / buffered Records queued / records in producer buffers
queued_records / queued_bytes Queue and writer in-flight budget
dropped / drop_reasons Total drops / drops by reason
emitted / by_level Enqueued records / per-level counts
write_failures / flush_failures / close_failures Sink failure counts
restarts / rollovers Writer restarts / file rotations
handler_stats Per-handler name/kind/native/writes/errors

drop_reasons includes overload, write_error, shutdown, no_handler, format, worker_dead, reentrant, rate_limited, and oversize. Prometheus metrics include tracing_logger_dropped_total, tracing_logger_emitted_total, tracing_logger_pending, tracing_logger_queued_bytes, and tracing_logger_handler_writes_total.

Multiprocess and instance lock

LoggerConfig(
    base_path="/var/log/app",
    name="worker",
    proc_split=2,          # include pid in file names; lock name follows
    instance_lock=False,   # or True; with proc_split each process gets its own lock
    when="D",
    keep=7,
)
  • proc_split=0 disables isolation; 1 uses the process name; 2 uses the pid.
  • With instance_lock=True, creating a logger takes <log file>.lock. A second process gets InstanceLockedError.
  • For multiple processes writing to one directory, use proc_split=1/2 or give each process its own directory.
  • Two logger names resolving to the same log file are rejected at assembly time, including Windows case folding.
  • After fork, call setup_logging in the child instead of reusing the parent runtime.

⚡ Performance

Numbers below are from Windows 10, 8 logical cores, release wheel, NullSink, single thread (2026-11-30):

Path Throughput
log.info / log.warning / log.warn (default template) about 1.0–1.2M records/s
log.error (auto_exc_info=True) about 1.1–1.2M records/s
log("INFO", ...) about 0.8–0.9M records/s
log(20, ...) about 1.1–1.2M records/s
log.info + fmt="%(message)s" about 1.6–1.7M records/s
log.info + log_batch=True + fmt="%(message)s" about 2.1–2.3M records/s
await log.ainfo(...) + fmt="%(message)s" about 1.0–1.1M records/s
  • 200 MB/s is byte throughput. The internal batch engine plus FileSink already exceeds it; the direct path at about 1.1M records/s × 180 B is about 200 MB/s. Plan durable bandwidth separately based on disk and sync_on_flush.
  • 2M records/s is direct-record throughput. It is reached with fmt="%(message)s" and log_batch=True.
  • 200M records/s is not realistic for direct Python calls on one machine. That scale requires block or byte-level batching.

Linux builds include the io-uring feature by default. File sinks try io_uring when first opened; Windows tries Overlapped + IOCP; if the kernel or syscall is unavailable, the sink falls back to BufWriter. The public configuration does not expose an I/O backend.

📦 Project Layout

Path Contents
python/tracing_logger/__init__.py Public API
python/tracing_logger/config.py LoggerConfig, path/level parsing, presets
python/tracing_logger/registry.py Registry, lifecycle, atexit/fork
python/tracing_logger/logger.py Logger facade
python/tracing_logger/protocol.py Sink / Handler protocols
python/tracing_logger/sink.py FileSink / ConsoleSink
python/tracing_logger/rotation.py Time and size rotation
python/tracing_logger/catch.py catch / acatch decorators
python/tracing_logger/metrics.py Prometheus text and JSON snapshots
python/tests/ Fast-path and regression tests

The hot path and sinks live in a native extension. Its source is maintained in a separate private repository and is not covered here.

🛠️ Development

python -m pytest python/tests -q

The public surface is python/tracing_logger/; fast-path regression tests live in python/tests/.

🤝 Contributing

Issues and pull requests are welcome. For larger changes, open an issue first. Before submitting, run the Python tests, check interface compatibility, and update the documentation. Performance changes should include a baseline, measurement environment, before/after numbers, and regression results.

🙏 Acknowledgements

The interface and semantics draw on common logging frameworks and the Rust tracing ecosystem. The bounded queue uses crossbeam-channel; the Python bindings use PyO3 and maturin. Archive compression uses flate2, zstd, lz4_flex, and rayon.

📈 Star History

Star History Chart

📄 License

MIT. See LICENSE.

Metadata

Release files for tracing-logger 0.1.1

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

Built distributions (wheels)

Table of built distributions (wheels) for tracing-logger 0.1.1
File Interpreter ABI Platform Actions
tracing_logger-0.1.1-cp312-abi3-win_amd64.whl CPython 3.12 abi3 Windows x86-64 Details for tracing_logger-0.1.1-cp312-abi3-win_amd64.whl
tracing_logger-0.1.1-cp312-abi3-manylinux_2_28_x86_64.whl CPython 3.12 abi3 Linux glibc 2.28+ x86-64 Details for tracing_logger-0.1.1-cp312-abi3-manylinux_2_28_x86_64.whl
tracing_logger-0.1.1-cp312-abi3-manylinux_2_28_aarch64.whl CPython 3.12 abi3 Linux glibc 2.28+ ARM64 Details for tracing_logger-0.1.1-cp312-abi3-manylinux_2_28_aarch64.whl

Total release size: 2.6 MB

Release files / tracing_logger-0.1.1-cp312-abi3-win_amd64.whl

Download URL tracing_logger-0.1.1-cp312-abi3-win_amd64.whl
Size 821.2 kB
Tags CPython 3.12 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
e154e90fc0bcd1ec215e88d6eaf1116abfacc0a4c4afe259da95259883e31012
BLAKE2b-256 checksum
How to use checksums
a68bf2f4c8d159826821b387603c8acaa5d6b18ad45f4295ed8000fa33891269
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / tracing_logger-0.1.1-cp312-abi3-manylinux_2_28_x86_64.whl

Download URL tracing_logger-0.1.1-cp312-abi3-manylinux_2_28_x86_64.whl
Size 934.1 kB
Tags CPython 3.12 Linux glibc 2.28+ x86-64 abi3
SHA-256 checksum
How to use checksums
c1993210a27d8df765fc40920dec9fb7561067f249388c6a3d34dbbdb7318550
BLAKE2b-256 checksum
How to use checksums
55a9440129b0e345c31ffc73e04f1b2a6cdd4a579503035ad77764ffbb5bbe97
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / tracing_logger-0.1.1-cp312-abi3-manylinux_2_28_aarch64.whl

Download URL tracing_logger-0.1.1-cp312-abi3-manylinux_2_28_aarch64.whl
Size 883.3 kB
Tags CPython 3.12 Linux glibc 2.28+ ARM64 abi3
SHA-256 checksum
How to use checksums
71b37ec26fb24d3c930afc53d6eef41ad04350c8740d92541b464371d1d46481
BLAKE2b-256 checksum
How to use checksums
0858a5bf8549e7e336d6a04b84aee5de0e5b68a2cdf539c448400fc2bfad6519
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for tracing-logger 0.1.1

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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.1 This release

3 release files No 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