Skip to main content Switch to mobile version tracing-logger 0.1.1 Thread-safe, asynchronous-friendly structured logger with a Rust core
pip install tracing-logger Copy PIP instructions
High-performance Python logging framework · bounded queue · rotation · compression · async · metrics
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.
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.
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.
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.
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") Recommended setups
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"].
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.
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
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
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:
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.
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 = 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:
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
With instance_lock=True, creating a logger takes
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.
Numbers below are from Windows 10, 8 logical cores, release wheel, NullSink, single thread (2026-11-30):
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.
The hot path and sinks live in a native extension. Its source is maintained in a separate private repository and is not covered here.
python -m pytest python/tests -q The public surface is python/tracing_logger/; fast-path regression tests live in python/tests/.
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.
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.
Released: Dec 2, 2026
Operating System OS Independent
Programming Language Python :: 3
Topic System :: Logging
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)
Total release size: 2.6 MB
Release files / tracing_logger-0.1.1-cp312-abi3-win_amd64.whl
Security for tracing-logger 0.1.1
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.
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
Dec 2, 2026 3 release files No provenance
"PyPI", "Python Package Index", and the blocks logos are registered trademarks of the Python Software Foundation.
© 2026 Python Software Foundation
Deployed from 147871d











