Release Notes¶
All notable changes to Logust, newest first. This page is generated from CHANGELOG.md.
Unreleased¶
0.6.1 - 2026-11-16¶
Fixed¶
- PyPy release builds: caller collection uses frame attributes on PyPy, whose C API lacks
PyFrame_GetBackand, on Python 3.11,PyFrame_GetCode. CPython keeps the existing native path. CI now tests PyPy 3.11 and 3.12 so build/import failures are caught before tagging a release.
0.6.0 - 2026-11-16¶
Upgrade notes¶
- Default console output moves to stderr and colors are detected automatically. Programs consuming logs from stdout need to select
sys.stdoutexplicitly or redirect stderr. See the detailed migration example under Changed. - Record values gain loguru-compatible types:
record["time"],record["elapsed"],record["thread"], andrecord["process"]are not directly JSON-serializable. Code serializing an entire filter/patcher/callback record needsjson.dumps(record, default=str)or an explicit subset of fields. Nativeserialize=Trueoutput remains supported. - Filters now enforce their documented behavior: string/dict filters take effect, and a callable filter that raises drops the record according to
catch=rather than letting it through. Unsupported rotation/retention strings now raiseValueErrorinstead of silently doing nothing.
Performance compared with 0.5.0¶
- Same-environment release-wheel comparison (10,000 messages, six independent processes/version): sync file output 14.84 → 6.89 ms on macOS (53.6% less time) and 17.47 → 8.80 ms in Linux ARM64 Docker (49.6%); JSON 15.60 → 7.39 ms (52.6%) and 18.13 → 8.78 ms (51.6%); async output including complete() 14.39 → 6.74 ms (53.1%) and 18.03 → 9.06 ms (49.8%). Apple M4 Pro, regular CPython 3.14.9, Rust 1.96.0; Linux runs in an OrbStack VM with container-local log files. Percentages are relative to 0.5.0, not the older cross-library snapshot.
- 32 additional common-API workloads checked on both systems: none met the predeclared repeated ≥5% slowdown screen. This is not an all-cases improvement claim: active exception output was 3.3% slower on macOS (1/6 pairs faster), with a mixed Linux result (median 2.9% faster, 2/6 pairs faster). One long-message pair on macOS was also more than 5% slower despite an improved median. The smaller intermediate-version enqueue regression from PR #103 remains unresolved; this cumulative comparison does not supersede it.
- Scope and evidence: output counts/content were checked after timing; all samples, adverse results, hashes and reproduction steps are retained in the 0.6.0 benchmark evidence. These regular-CPython results do not establish free-threaded, Windows, x86-64 Linux or all-configuration performance. Linux Docker validation: Python 1,342 passed / 2 skipped, Rust 127 passed, plus 0.6.0 installed-wheel/version checks.
Added¶
- Python 3.15 support: CI tests CPython 3.15 and free-threaded 3.15t on Linux, macOS, and Windows, including a check that importing Logust keeps the GIL disabled. Free-threaded release builds now target both 3.14t and 3.15t. The Rust bindings use PyO3 0.30.1, and source builds require maturin 1.14.1 or newer. Python 3.10 remains the minimum supported version.
buffering=for file sinks: theopen()argument loguru passes through.buffering=1writes each line to the file before the logging call returns (onewrite()per message, as loguru andlogging.FileHandlerdo), so logged lines are visible totail -fright away and survive a process killed bySIGTERM(Uvicorn re-raises it after a graceful shutdown), stopped withos._exit(), or crashed; nofsync()is done.buffering=Nsets the buffer size in bytes, and a negative value means 8192, as inopen(). The default is unchanged: an 8 KB buffer for sinks without rotation, one write per line for sinks with rotation.buffering=0raisesValueError(open()rejects unbuffered text files), a non-intraisesTypeError, and passing it to a stream or callable sink raisesTypeErrorlikemodeandencoding. It is ignored withenqueue=True, whose writer thread batches on its own. Accepted byconfigure(handlers=[...])andHandlerConfig. Per message with the default format: about 0.9 µs by default, 2.5 µs withbuffering=1(bench_throughput.py, 10,000 messages: 29.8 ms, against 89.4 ms for loguru and 83.4 ms forlogging).logger.catch()matches loguru's call shapes: use it without parentheses (@logger.catch) or as a context manager (with logger.catch():). Newonerror,exclude, anddefaultoptions;levelaccepts custom level names and numbers. Coroutine and generator functions are decorated correctly.logger.level()lookups and updates:logger.level("INFO")returns aLevel(name, no, color, icon)named tuple, andlogger.level("INFO", color="blue")(nono) updates an existing level, including the console color of built-in levels. Unknown names raiseValueError.Levelis exported fromlogust.datetimerotation values:add(rotation=...)acceptstimedelta(days=1),timedelta(hours=1), andtime(0, 0). Values that can't be honored exactly raiseValueError.logger.parse(): the module-levelparse()is also available on the logger, as in loguru.- Positional message arguments:
logger.info("Processed {} items", 42)now works like loguru on every level method,log(),exception(),opt(), and the module-level functions (logust.info(...)). Positional and keyword arguments can be mixed, kwargs not used by a placeholder still go toextra, and a message logged without arguments is never formatted. Filtered-out calls now return before any argument handling, making them about 30% faster than in 0.5.0. - loguru format fields:
{level.name},{level.no},{level.icon},{thread.name},{thread.id},{process.name},{process.id},{file.name}, and{file.path}work in format strings on every sink type, and the caller, thread, and process info they need is collected automatically. Built-in levels get loguru's default icons (FAIL, which loguru lacks, gets✖️). {exception}in format strings: the traceback is written where{exception}stands and is no longer appended after the message, so it is printed once. It is empty for records without an exception.- More
compressionformats: file sinks accept loguru's format strings"gz","bz2","zip","tar","tar.gz"and"tar.bz2", and rotated files get the matching extension (for exampleapp.<timestamp>.pid<pid>.log.zip).compression=Truestill means gzip."xz","lzma"and"tar.xz"raiseValueError. Retention removes rotated archives in every supported format. Compression still only runs at rotation, so writes are not affected mode=for file sinks:"a"(default) appends and"w"truncates the file when the sink first opens itdelay=Truefor file sinks: the file and its parent directories are created when the first message is written, so a sink that never logs leaves nothing on diskencoding=for file sinks: accepted for loguru compatibility. Files are always written as UTF-8, so UTF-8 aliases are accepted and other encodings raiseValueErrorcatch=for every sink type:Trueprints a loguru-style report to stderr when a sink fails, andFalseraises the error from the logging call (OSErrorfor file sinks). The defaultNonekeeps the previous silent behavior; loguru's default iscatch=True. Console sinks (sys.stdout,sys.stderrand the default handler) follow the same policy, withFalseraisingBrokenPipeErrorwhen the reader of a pipe has gone away.enqueue=Truefile sinks are not covered yet: the background writer of anenqueue=Truesink reports write errors to stderr whatevercatchis.mode,encodinganddelayraiseTypeErrorfor stream and callable sinks, as in loguru. All five options also work inconfigure(handlers=[...])- Per-module
enable(name)/disable(name):logger.disable("mylib")drops messages logged frommyliband its submodules, andlogger.enable("mylib")turns them back on, with loguru's rules (dotted prefix match, most specific rule wins,""means all modules). Rules are shared by bound and patched loggers, apply tolog(),exception(),opt()andcatch(), are available aslogust.enable()/logust.disable()andconfigure(activation=[...]), and match the stdlib logger name for records forwarded byInterceptHandler.enable()/disable()without a name andenable("INFO")(any built-in level name) still toggle the console, unlessdisable(name)left a rule for a module of that name (disable("info")is undone byenable("info")). Logging cost is unchanged while no module is disabled backtrace=anddiagnose=per handler:add()andconfigure(handlers=[...])accept loguru's options for tracebacks logged byexception(),catch()andopt(exception=True). Each handler gets its own variant, and each variant is formatted once per logged exception. Both default toFalse, unlike loguru, becausediagnosewrites variable values into the logs.opt(backtrace=, diagnose=)still applies to every handler for one message. Messages without an exception are not affected.{extra}format token: writes the whole extra dict as loguru does ({'user': 'alice', 'attempt': 2}), on every sink type. Strings are quoted likerepr(); keys are sorted, and types other thanstr, numbers,bool,None, lists, tuples and dicts usestr().opt(colors=False): keeps color markup in that message as plain text on every sink. Message markup is still parsed by default, soopt(colors=True)changes nothing (loguru only parses message markup withcolors=True).opt(capture=False): keyword arguments only format the message and are not added toextra, as in loguru.- loguru-shaped record dicts: filters, patchers, and
add_callback()callbacks can use loguru's record fields:record["level"].no/.name/.icon,record["time"](an awaredatetime),record["elapsed"](atimedelta),record["file"].name/.path,record["thread"].id/.name,record["process"].id/.name, andrecord["module"].record["level"]andrecord["file"]arestrsubclasses, sorecord["level"] == "INFO"keeps working, and the flat keys (level_no,timestamp,thread_id, ...) stay. The value types (RecordLevelStr,RecordFile,RecordThread,RecordProcess,RecordElapsed) are exported fromlogust. Logging without a filter, patcher, or callback is unaffected; a filter that runs on every message costs about 0.1 µs more per message
Changed¶
- Cheaper message-only file output: synchronous native file sinks without rotation and with
format="{message}"reuse the message text without a temporary formatting allocation when no exception is appended. Message markup and exception rendering are unchanged; JSON and queued handlers keep their owned formatting path, and rotating sinks retain owned write buffers. - Suppressed exceptions skip traceback formatting:
exception(),opt(exception=True),catch()and intercepted stdlib records check the level and module rules before rendering a traceback.catch()still appliesonerror,defaultandreraisewhen its log message is suppressed. - Cheaper per-call context and severity-scoped collection: adding extra fields shares existing immutable text/JSON values instead of copying bound JSON trees. Higher-threshold sinks, filters, and callbacks no longer force caller/thread/process collection for lower-severity records.
- Less allocation in native JSON output: file and console sinks with
serialize=Trueborrow the usual timestamp from a stack buffer instead of allocating a temporary string for each record. Timestamp text, JSON fields and escaping are unchanged, including signed years and leap seconds. - Cheaper native JSON output: file and console sinks write fixed JSON keys and the ordinary timestamp directly, including records with caller, extra or exception fields. Serde still serializes every value, preserving string escaping, field order, omission rules and signed-year output.
- Cheaper automatic caller collection: CPython 3.11+ avoids a generic frame attribute lookup while preserving dynamic module names, source paths and stack depth. Python 3.10 retains the existing retrieval path.
- BREAKING: the default console handler writes to stderr and detects colors, as in loguru: the handler
loggerstarts with (and the oneenable()adds when there is no console handler) wrote to stdout and always emitted ANSI colors, even when piped, redirected to a file, or withNO_COLOR=1/TERM=dumb. It now writes to stderr, and uses colors only whenlogger.add(sys.stderr)would:NO_COLOR,FORCE_COLOR, known CI services, PyCharm, Jupyter,TERM=dumb, then whether stderr is a terminal. The decision is made once, when the handler is created (at import for the globallogger), so logging costs the same as before (about 1.2 µs per message either way). To keep the old destination, replace the default handler:logger.remove(); logger.add(sys.stdout)(addcolorize=Trueto also keep colors when stdout is not a terminal). Programs that read the logs from a pipe on stdout (python app.py | grep ...) now need2>&1. - Cheaper records in the Rust core: each record reads the system clock once instead of twice (the local UTC offset is reused within the same second and still follows
TZand/etc/localtimechanges within a second, as before), records below every sink's level return before taking any lock and the callback list is only locked when a callback can take the record, custom levels share one registeredLevelInfoinstead of copying its name, color and icon per record, and the default{time}digits skip a redundant UTF-8 check. Per message, directly on the Rust logger: file sink with{message}146 → 124 ns (-15%), bound logger -17%, default format with caller info -12%,enqueue=True-14%, custom level -25%, callable sink{message}-8%,serialize=True-7%, filtered-out call -7%. Output is unchanged. - Faster callable sinks, filters and callbacks: callable sink templates are compiled once into a single rendering function, formatted sinks at custom levels and
serialize=Truesinks get only the record fields they use, and the loguru-shaped record values are cheaper to look up. Per message, a callable sink with the default format is about 33% faster, with{message}20%, with a rich format ({time:...},{level.icon},{thread},{extra}) 37%, a custom level to a callable sink 39%, aserialize=Truecallable sink 9%, a callable sink with a filter 14–29%, and file sink filters, patchers andadd_callback()callbacks 3–11%. Output is unchanged. - Plain calls cross into Rust once:
logger.info("msg")(and the other level methods,log("INFO", ...), bound loggers andlogust.info(...)) with no arguments, exception, patcher or module rule now hands the message to Rust, which collects the caller frame, thread and process itself from the handlers' needs instead of the Python wrapper readingsys._getframeand passing keyword arguments. Measured per call with a file sink (median of alternating runs, noise 1–2%):{message}0.38 → 0.26 µs, default format 0.74 → 0.57 µs,{name}:{function}:{line}0.67 → 0.49 µs,{thread.name}:{process.name}0.75 → 0.47 µs,log("INFO", ...)0.49 → 0.34 µs,serialize=True0.84 → 0.72 µs, callable sinks 1.2–1.3x. Records are identical; calls with arguments,exception=, a patcher, a disabled module or a fixedCallerInfokeep the Python path and cost about the same as before (3–13% more for the checks), and filtered-out calls are unchanged. logger.level()returns the level: registering a level now returns itsLevelinstead ofNone,nomay be passed positionally, and re-registering keeps the existing color and icon unless new ones are given. Changing thenoof a built-in level raisesTypeError(as in loguru); a custom level re-registered under a newnoreleases the old one.- Messages logged from inside a callable sink are delivered: a sink that itself calls
logger.info(...)used to have those nested messages dropped. configure(levels=...)entries withoutnoupdate existing levels: previously they were silently skipped; an unknown name now raisesValueError.- logust's frames are left out of tracebacks: the
catch_wrapperframe added by@logger.catchno longer appears.opt(backtrace=True)/opt(diagnose=True)tracebacks now hide only logust's own modules; before, they hid every frame whose path containedlogust, including application code in such a directory. - Callable sinks skip markup parsing for messages without
<: a{message}-only callable sink is a few percent faster. record["elapsed"]is atimedeltain filters, patchers, and callbacks. Itsstr()and{elapsed}still giveHH:MM:SS.mmm, but comparing it to a string no longer matches.time,elapsed,thread, andprocessare not JSON-serializable, so a callback passing the whole record tojson.dumps()needsdefault=stror a subset of keys. Bound values namedtime,module,thread,process, orlevel_nonow stay only inrecord["extra"]instead of also shadowing the top-level keyrecord["exception"]is always present:Nonewhen there is no exception (it was missing before), as documented. It is still the traceback text, not loguru's(type, value, traceback)tuple- Patcher records gain fields:
time,timestamp(previously""),elapsed,thread, andprocessare available, computed on first access so patchers that only touchrecord["extra"]cost the same as before, andrecord["level"]has.no. Changes tomessage,extra, andexceptionare still the only ones applied - Caller file path is collected without extra cost: the Python side now passes the code object's path and Rust derives the basename, which also makes formats with caller info slightly faster.
{file}and the record dicts'filekey are still the basename. - Faster file and console output: the default
{time}is written directly instead of through chrono's strftime parser, colorized tokens are rendered in place instead of through a temporary string each, padded levels and numbers are pushed as digits, and locked writes of rotating sinks no longerdup()the lock file per record. Output is byte-identical. Measured per record on a release build (median of alternating runs, noise 2-5%): default file sink 1.16 → 0.88 µs,serialize=True1.19 → 0.98 µs, rich template ({thread},{process},{elapsed}) 1.60 → 1.27 µs, colorized file sink 1.45 → 0.96 µs, colorized console 2.12 → 1.66 µs,enqueue=True1.17 → 0.92 µs.{message}-only sinks are unchanged. - Less Python overhead per message: the dispatch path skips the patcher call when no patcher is set, reads cached collection requirements inline, memoizes which kwargs a message template consumes, builds
bind()loggers without re-running__init__, and binds the module-level functions (logust.info(...)) once at import. Measured per call with a file sink:logger.info("msg")with{message}about 25% faster (0.48 → 0.36 µs) and about 9% with the default format,logust.info(...)47%,logger.info("x {y}", y=1)33%,opt(lazy=True)31%,bind(k=1).info(...)29%,log("INFO", ...)21%,patch(f).info(...)14%, callable sinks 17%. Output and caller depth are unchanged; filtered-out calls and the default console handler cost the same as before.
Fixed¶
- File rotation counts buffered bytes: size-based rotation with
buffering=Nnow includes lines still in memory, rather than resetting the size to the shorter file on disk. The existing rotation lock still checks the flushed file before renaming it, and buffered lines follow a rotation performed by another process. Retention also works with bare relative filenames such as"app.log"; previously the first rotation could fail its directory scan and silently drop subsequent logs with the defaultcatchsetting. - Exception-group traceback cycles: enhanced tracebacks no longer raise
RecursionErrorwhen a child exception's cause or context refers back to its group, including a child re-raised while handling the group. Repeated members retain their own tracebacks in each branch. opt(capture=False)respects suppression before formatting:log()and the level methods no longer format keyword arguments when the level or caller's module is disabled. Unknown levels still raiseValueError.- Intercepted stdlib records run the target's patchers:
InterceptHandler(target=logger.patch(...))and configured patchers now apply message and exception redaction, extra changes and patcher chains. Contextualized and bound values follow normal precedence, and per-handlerbacktrace/diagnoseoptions apply to intercepted exceptions. Caller fields remain empty, and module activation still matches the stdlib logger name. - Callbacks and filters can reconfigure the logger without deadlocking: Python sinks and filters run against a snapshot of the current destinations, with configuration locks released. Adding a handler from another thread while a sink releases the GIL, or removing a handler from a filter/callback, no longer hangs. A record finishes using its original destinations; additions and removals apply to later records. Removed filters and callbacks are finalized outside the locks, and destinations added by their finalizers keep their bookkeeping. File-only logging keeps its existing allocation-free configuration lookup.
- Python format specs work in file and console sinks (breaking for invalid specs): the Rust formatter only applied
{level:<N}and{time:<spec>}and wrote every other spec out literally, so loguru's own default format ({level: <8}),{line:05d},{level:>8},{message:>20}or{extra[user]:<10}printed{level: <8}instead of a padded level, and the same format gave different output in a callable sink. Every token except{time}and{extra}now takes Python's full format-spec mini-language ([[fill]align][sign][z][#][0][width][grouping][.precision][type]: fill and alignment, zero padding, string truncation,,/_grouping, and thed,n,b,o,x,X,c,e,f,g,%types for the integer tokens{line},{level.no},{thread.id},{process.id}), with exactly the output offormat(value, spec)in every sink type. Widths count code points, as in Python, and color codes take no width (<level>{level: <8}</level>pads inside the color, as in loguru). Specs are compiled once when the sink is added, and an invalid one ({message:d},{level:=8},{line:.2d}) now raisesValueErrorinadd()with Python's message, for callable sinks too, which used to write the value unformatted.{extra[key]:<spec>}formats the value's text, as callable sinks always did: a spec only a number accepts ({extra[count]:05d}) writes the value as is, and a spec no value accepts raises. Formats without specs render exactly as before, at the same speed (file sink, release build: default format 1.64M logs/s before and after, loguru's default format 1.44M → 1.47M logs/s,bench_format_record.py0.88–1.03M → 1.06–1.12M logs/s, within noise). - Custom levels and numbers work as level thresholds:
logger.add(sink, level="NOTICE")(console, file, callable andserialize=Truesinks),logger.set_level("NOTICE"),logger.enable(level="NOTICE"),logger.add_callback(level="NOTICE"),logger.is_level_enabled("NOTICE")andconfigure(handlers=[{"level": "NOTICE"}])raisedAttributeError: type object 'builtins.LogLevel' has no attribute 'Notice'for a level registered withlogger.level(), andlevel=25raisedTypeError. As in loguru, a threshold is now a level name (built-in or custom, case-insensitive), anint>= 0 or aLogLevel, and a record passes when itsnois at least that number, so custom levels between the built-ins are filtered correctly (withNOTICEat 23,level="NOTICE"dropsINFOand keepsNOTICE,SUCCESSandWARNING). An unknown name raisesValueError(Level 'NOPE' does not exist), a negative numberValueError, and any other typeTypeError, before the sink is created.get_level()returns anintwhen the console threshold is not a built-in level's number.examples/06_custom_levels.pyruns again. Handlers now store the threshold as a number, so the level check is the same integer comparison as before; per-call times are unchanged within noise. logger.log(LogLevel.Warning, ...)works:log()andopt().log()accept aLogLevelas well as a name or number; it used to raiseValueError: Invalid log level.LogLevelmembers can be ordered:LogLevel.Info < LogLevel.ErrorraisedTypeErroralthough the type stubs declared the comparison operators;<,<=,>and>=now compare by severity, andsorted()works.- File sinks lost lines at normal exit when a filter or a callable sink was set:
logger.add("f.log", filter=lambda r: True); logger.info("one")leftf.logempty unlesslogger.complete()was called, for sync andenqueue=Truesinks alike, and so did adding any callable sink. Buffered lines were only written when the logger was freed during interpreter teardown, and a filter or sink defined in a module refers to that module's globals, which hold the logger: the reference cycle kept it alive past finalization, so it was never freed. Buffered sync sinks andenqueue=Truesinks are now written from anatexithandler registered at import, which runs after the application's ownatexithandlers and does not depend on the logger being freed. Logging speed is unchanged. enqueue=Truesinks flush within 100 ms under a steady trickle of messages: the background writer only flushed after 100 ms without any message, so a message every few tens of milliseconds kept lines in its buffer until 8 KB had accumulated. Every line now reaches the file at most 100 ms after it was logged.- File lines are never split between two writes: a line that didn't fit in the rest of the 8 KB buffer, or was longer than it, went to the file in two
write()calls, so another process appending to the same file could land in the middle of it. The buffer is now written first, and a line longer than the buffer is written in one call. disable()/enable()keep your console handlers:disable()dropped every console handler, including those added withlogger.add(sys.stdout)/logger.add(sys.stderr), andenable()then added the default handler instead of them.disable()now sets the console handlers aside andenable()puts them back with their format, filter, colors and ID; the default handler is only added when there is no console handler to bring back (for example afterlogger.remove()).remove(handler_id)also removes a handler that is switched off, andset_level()applies to it. File and callable sinks are untouched, as before.enable(level=...)sets the level when the console is already on: the level was ignored unless the call added the handler back. It now sets the level of every console handler, likeset_level().- String and dict filters work (breaking for code that passed them):
add(filter="mypkg")andadd(filter={"": "WARNING", "mypkg": "DEBUG", "noisy": False})were accepted and had no effect, so every record reached the sink. They now follow loguru: a string keeps the records of that module and its submodules ("a"matchesaanda.b, notab;""matches all), and a dict sets a minimum level per module, decided by the closest parent module in the dict, with""as the default and values given as a level name, a number,True(all) orFalse(none). Both are checked in Rust on the caller's module name, without building the record dict or calling Python: a file sink withfilter="mypkg"costs about 0.53 µs per message, against 1.3 µs for the equivalentlambda r: r["name"] ...function and 0.21 µs with no filter (the difference is the caller lookup the module name needs, the same as{name}in a format). They work on file, console, stream and callable sinks and inconfigure(handlers=[...]), and the type hints ofadd()andHandlerConfigaccept them (the newlogust.FilterTypealias). Invalid filters now raise atadd()time like loguru:TypeErrorfor a filter that is not a string, dict or callable, a non-string dict key or a dict value of another type, andValueErrorfor an unknown level name, a negative level or the built-infilter()function. - A filter that raises drops the record and follows
catch=(breaking): on file and console sinks, an exception raised by afilterfunction used to be swallowed and the record was written anyway. Now, as in loguru, the record is not written to that sink, and the error follows the sink'scatch=policy: dropped silently with the defaultNone, reported to stderr as--- Logging error in Logust Handler #<id> ---with the traceback forTrue, and raised from the logging call (after the other sinks got the record) forFalse. Callable and stream sinks already behaved this way. - Console sinks no longer crash on a closed pipe: when the reader of stdout or stderr went away (
python app.py | head -1), the nextlogger.info(...)tosys.stdout,sys.stderror the default handler escaped aspyo3_runtime.PanicException(aBaseException) and took the application down. Console writes now return the error to the sink'scatchpolicy:None(default) keeps running and drops the output,Trueprints one report per dropped message,FalseraisesBrokenPipeError. Output timing is unchanged (one line-buffered write per message), and thecatch=Truereport and theenqueue=Truebackground writer no longer panic when stderr itself is broken. - Unsupported
rotation/retentionstrings are rejected: values the file sink does not understand, such as loguru'srotation="1 week"or"12:00"andretention="1 week", were accepted and then never rotated or cleaned anything up.add()now raisesValueErrorlisting the supported forms ("daily","hourly", sizes like"500 MB"; retention as a file count or"N days"). enqueue=Truein a forked child on macOS: a child forked after the parent had run anenqueue=Truesink crashed with SIGTRAP when it added its ownenqueue=Truesink, because Rust's thread parking on macOS uses libdispatch, which traps after fork(). Sinks created in a forked child on macOS now write synchronously, as inherited sinks already did.- Coroutine function sinks are rejected:
add()raisesTypeErrorforasync defsinks (and async callables) instead of accepting them and never awaiting the coroutine. opt()formats the message once:logger.opt().info("{} {user}", value, user="bob")no longer raisesKeyError, and braces inside a positional value are no longer re-interpreted as placeholders.{time:<spec>}follows the spec: loguru time tokens (YYYY-MM-DD HH:mm:ss.SSS,A,ZZ,[escapes],!UTC, ...) and%strftime specs were ignored: file and console sinks wrote{time:...}literally and callable sinks wrote the full RFC 3339 timestamp. The spec is compiled once when the handler is added, and an invalid spec raisesValueError. Plain{time}is unchanged.contextualize()is context-local: it swapped the shared logger's context in place, so concurrent asyncio tasks and threads saw each other's values and a block exiting restored another block's stale snapshot; with the Starlette/FastAPI middleware, handler lines under concurrent requests carried another request'srequest_id. The values now live in acontextvarsvariable, as in loguru: each thread and task sees only its own blocks (and those inherited from the task that started it), nested blocks merge and restore correctly, and the values apply to every logger, bound or not, and tologust.info(...).extrafollows loguru's precedence:contextualize()values, thenbind()values, then the message's keyword arguments. The block still yields the logger. A plainlogger.info("msg")inside a block stays on the Rust fast path with a per-thread cache of the merged context; measured per call with a file sink (median of alternating runs, noise about 3%), logging inside a block costs the same as outside (0.21 µs with{message}), and the cost outside any block is unchanged.- Time-based rotation across daylight saving changes:
rotation="daily"and"hourly"(and thetimedelta/time(0, 0)forms) stopped rotating for good when the next boundary was a wall-clock time that repeats (clocks fall back) or does not exist (clocks spring forward), which every zone with DST hits for"hourly"and zones that change at midnight, such asAmerica/SantiagoorAmerica/Havana, hit for"daily". A repeated boundary now rotates once, at its first occurrence, and a skipped boundary rotates at the transition itself, as in loguru. If the boundary cannot be resolved at all, the sink falls back to one hour or one day after the previous rotation instead of never rotating again. - Log files from an earlier period rotate on the first write: a
"daily"or"hourly"sink added over a non-empty file that was last written before the current boundary (for example by yesterday's run) rotates it on the first write, as loguru does. Previously the old content stayed in the file until the next boundary, and short-lived processes that never ran across one never rotated.
0.5.0 - 2026-10-01¶
Added¶
- Stream sinks:
logger.add()accepts any object with a callablewrite()(e.g.io.StringIO, a redirectedsys.stdout). Onlysys.__stdout__/sys.__stderr__use the Rust fast path. Item 1 from issue #59 (#64) colorizefor every sink type: callable and file sinks acceptcolorize=True(level colors, token styles, message markup). Item 2 from issue #59 (#65)richprogress bar example:examples/09_rich_progress.pylogs above a live progress bar. (#65)
Changed¶
- Color markup is stripped from non-colorized output: Item 3 from issue #59 (#61)
- Stream
colorizeauto-detection follows loguru:NO_COLOR,FORCE_COLOR, CI, PyCharm, Jupyter, andTERM=dumbare honored beforeisatty().serialize=True, file, and callable sinks default to no color. (#65)
Fixed¶
- Color markup in the
formatstring: tags such as<green>{time}</green>and loguru's<level>...</level>are rendered when colorized and stripped otherwise, on every sink type. A token inside markup takes the markup's color instead of its default style. (#66) - Callable sinks include tracebacks: formatted callable sinks now append the exception text, the same as file and console sinks. (#64)
0.4.2 - 2026-08-06¶
Changed¶
- Dropped the unused
parking_lotbuild dependency: sink, level, and logger state has usedstd::syncprimitives since thefork()-safety work in 0.3.1, soparking_lotwas no longer referenced anywhere insrc/and was not pulled in transitively either. Removing it shrinks the build graph for anyone compiling Logust from source; no runtime or API behavior changes. The contributing guide now documentsstd::syncas the expected lock choice. (#56)
0.4.1 - 2026-06-14¶
Fixed¶
- Free-threaded release CI targets supported interpreters and platforms: release wheel builds no longer target unsupported Python 3.13t, keep Python 3.14t free-threaded validation, and add Windows 3.14t free-threaded wheels for x64, x86, and arm64. (#48)
0.4.0 - 2026-06-14¶
Added¶
- Canonical request events for web integrations:
logust.contribnow providescanonical_event(),add_event_fields(),clear_event_fields(),get_event_fields(),get_current_event(), andTailSampler, and Starlette/FastAPI middleware can emit onehttp.requestevent per request with request/response fields, endpoint-enriched extras, and tail sampling for errors and slow requests. (#38)
Changed¶
- JSON extra values handle more Python types:
serialize=Truenow emitsbytes/bytearrayextras as UTF-8 strings with replacement for invalid bytes,set/frozensetextras as arrays,datetime/date/timeextras as.isoformat()strings, andEnumextras via their.valueconverted with the same rules. Text formatting ({extra[key]}) and Python callback records still use the existingstr(value)view. Other object types such asDecimal,UUID,Path, andcomplexcontinue to fall back tostr(value)in JSON.
0.3.2 - 2026-05-07¶
Added¶
- Loguru-style kwargs-to-extra in log methods:
logger.info("user {id}", id=1, action="x")now formats the message withstr.formatand attaches any kwargs not consumed by the message placeholders torecord["extra"]for that call only (no persistent bind). Works ontrace/debug/info/success/warning/error/fail/critical/log/exception. When the level is disabled,message.format(**kwargs)is skipped entirely via the existingmin_levelearly-return, so disabled-level calls never trigger format work or__format__-side effects. Field root detection treats{0abc}and other non-decimal roots as keyword references. Implementation is Python-only — no Rust or.pyichanges — and per-call extra values are coerced to strings via the same path asbind(). (#25) logust.contrib.starlettehonors incomingx-request-idheader:RequestLoggerMiddlewarenow propagates the upstreamx-request-idheader value as the request id when present, falling back to the existing 8-charuuid4otherwise. Improves log correlation across reverse proxies. Visible behavior change for users behind proxies that already set the header — log ids will look different from before. (#28)- Optional extras
[starlette]and[fastapi]:pip install "logust[starlette]"/pip install "logust[fastapi]"install the framework alongside Logust sologust.contrib.starletteworks without extra steps. (#29)
Fixed¶
- Patcher pipeline runs before handlers see the record:
Logger.patch()previously registered a callback that was never invoked before records reached filters or sinks, so security-sensitive transforms (e.g. token redaction) were silently dropped._log_with_leveland the dynamic-levellog()path now run patchers before binding extras, normalize patched-extra keys tostrfor the Rust binder, and blank removed keys ("") so a patcher can hide a value previously bound viabind()/contextualize(). Behavior fix: code that relied on the silent drop (unlikely) will now see patchers run. (#26) - Starlette middleware no longer leaks secrets via query strings or partial JSON bodies:
query_paramswas logged as a plaindict(...), exposingaccess_token/password/ etc. in cleartext. Body masking ran after truncation, so a request that exceededmax_body_sizecould still log the unmasked head. Query params are now masked through the same sensitive-key check as headers, multi-value params are preserved, and bodies are masked first then truncated. (#26) - File retention no longer deletes unrelated same-stem files: The retention scan in
src/sink.rsusedfilename.starts_with(stem), so a sibling likeapp.keep,app.log.bak, or evenapplication.lognext toapp.logwas eligible for deletion. Matching is now strict: only filenames matching the generated rotation pattern{stem}.{YYYY-MM-DD_HH-MM-SS}_{micros}.pid{N}.{ext}[.gz]are considered. (#26)
Changed¶
RequestLoggerMiddlewarerejects negativemax_body_size:__init__now raisesValueErrorwhenmax_body_size < 0instead of silently producing surprising slicing behavior. (#28)
0.3.1 - 2026-04-23¶
Fixed¶
FileSink::droppanic in forked children (enqueue=True): When a process using anenqueue=Truefile handler was forked (e.g. viamultiprocessing.Process), the child inherited the parent'sJoinHandlepointing at a background writer thread that does not survivefork(). Callinglogger.remove()(or exit cleanup) in the child triggeredthreads should not terminate unexpectedly.FileSinknow records its creation PID and skips theJoinHandle::joinin non-original processes, preventing the panic. (#22)- Fork-safe file sinks across parent/child processes: On Unix,
FileSinknow registers async sinks in a global registry and uses apthread_atfork(prepare)hook to pause writer threads beforefork(), avoiding macOSlibdispatchSIGTRAP from inheriting live threads. The parent resumes its async writer on the next use; forked children downgrade an inheritedenqueue=Truebackend to a fresh synchronousBufWriteron their first write instead of reviving the parent's thread and channel, andmem::forgetthe inherited handle/sender/buffer so no cleanup ever runs against parent-owned state. Multiple forked processes can keep appending to the same file sink, and re-forking a child no longer reintroduces the original join panic. (#22) - Cross-process rotation and
max_size: Rotation is now coordinated across processes withflockon a sibling<path>.lockfile — writers takeLOCK_SHfor each write while the rotator takesLOCK_EX, sorename/compress/ retention only run once every other process has released the old inode. Writers detect the inode change viastatand reopen the file on their next write, so no lines are lost when multiple processes share the sink.max_sizealso re-checks the real file size withfs::metadataafter the atomic fast path, so size-based rotation no longer undercounts concurrent writes from other processes. Follow-up hardening: async shutdown stops the writer by dropping the sender instead of enqueueing a blockingShutdown,pthread_atfork(prepare)usestry_lockbest-effort shutdown without temporary allocation, and the sink / level / logger state usesstd::syncprimitives instead ofparking_lotto keep inherited mutex state well-defined acrossfork().
0.3.0 - 2026-04-11¶
Performance¶
- Formatting hot path (Rust, non-color):
format_record_templatewrites padded level, line, thread, process, and elapsed into the output buffer withstd::fmt::Writewhere possible, avoiding per-tokenString/format!temporaries; colorized branches unchanged.format_templateskips time/level/message work when those tokens are absent (TokenRequirements). Addedbenchmarks/bench_format_record.pyfor a rich-template throughput check. - Formatted callable sink (built-in
logger.add,filter=None,serialize=False): Rust distinguishes rawadd_callbackfrom formatted sinks and builds a minimal record dict per template flags (seeParsedCallableTemplate::lightweight_requirements_for_rust()), instead of always callingbuild_record_dict. Python still runsParsedCallableTemplate.format()for full template/spec compatibility. Nestedrecord["extra"]is populated only whenextra[...]tokens are used (no duplicate flat extra keys on the lightweight path). Custom-level logs (_log_custom) keep the previousbuild_custom_record_dictpath for all callbacks. update_requirements_cache(Rust): Merges per-sinkFormattedSinkRequirementsintoTokenRequirementsinstead of forcingTokenRequirements::all()whenever any callback exists; raw callbacks still force the full requirement set.- Non-color
format_record_template(Rust): Avoids an extraStringallocation for{level}/{message}when ANSI coloring is off; colorized output still reuses precomputed strings for repeated tokens. is_level_enabled()(Rust): Uses the existingcached_min_levelatomic instead of scanning every handler and callback, so enablement checks are O(1). This makes disabledlogger.opt(lazy=True).…cheap even with large sink lists. Added regression tests (callback-only andremove_callback) andbenchmarks/bench_lazy_is_level.py.- Filter fast path (Rust): Logs no longer enter the GIL path solely because a lower-priority handler has a Python
filter. Handler filters run only after the handler's level gate passes. Removed the unusedcached_has_filterscache; token requirements still treat any present filter as requiring full record fields for Python dict building.
0.2.1 - 2025-12-27¶
Added¶
CollectOptionsfor per-handler information collection control- Callable sinks with custom format templates
{thread},{process},{file},{elapsed}format tokens
Performance¶
- 14x faster than loguru on average (up from 1.9x in 0.1.0)
- 4x faster than Python logging on average
- Cached requirements computation (O(1) hot path)
- Cached
has_filtersflag in Rust (eliminates per-log iteration) - Lazy token value generation for callable sinks
- Pre-aggregated CollectOptions to avoid per-log dictionary traversal
- Optimized kwargs passing in hot path
0.2.0 - 2025-12-25¶
Added¶
Caller Information¶
- Caller info (module name, function name, line number) in log output
- New format tokens:
{name},{function},{line} - Default format now includes caller info:
{time} | {level:<8} | {name}:{function}:{line} - {message} - Caller info included in JSON serialized output
Console Sink Support¶
logger.add(sys.stdout)andlogger.add(sys.stderr)supportcolorizeparameter for console handlers- Auto-detect colorize based on TTY when not specified
Changed¶
opt(depth=N)now correctly adjusts caller frame for caller info- Performance optimization: level check before frame capture
Fixed¶
- Caller info now shows correct location through
opt(),exception(),catch()wrappers - Thread-safe colorization (removed global
set_override)
0.1.0 - 2025-01-XX¶
Added¶
Core Features¶
- 8 log levels: TRACE, DEBUG, INFO, SUCCESS, WARNING, ERROR, FAIL, CRITICAL
- Colored console output with automatic terminal detection
- File output with buffered writing
File Management¶
- Size-based rotation (
"500 MB","1 GB") - Time-based rotation (
"daily","hourly") - Retention policies (by days or file count)
- Gzip compression for rotated files
- Async file writing with
enqueue=True
Formatting¶
- JSON serialization with
serialize=True - Custom format templates with placeholders
- Color markup support (
<red>,<bold>, etc.)
Context & Binding¶
bind()for permanent context attachmentcontextualize()context manager for temporary context- Extra fields included in JSON output
Exception Handling¶
catch()decorator for automatic exception loggingexception()method for logging with tracebackopt(exception=True)for capturing current exceptionopt(diagnose=True)for variable inspectionopt(backtrace=True)for extended stack traces
Advanced Features¶
- Custom log levels with
level() - Log callbacks with
add_callback() - Handler filtering with
filterparameter - Lazy evaluation with
opt(lazy=True) configure()for batch configuration- Log file parsing with
parse()andparse_json()
Developer Experience¶
- Full type annotations (PEP 561 compatible)
- loguru-compatible API for easy migration
- Comprehensive test suite
Performance¶
- Rust-powered core for high throughput
- 1.9x faster than loguru on average
- 1.3x faster than Python standard logging
- Lock-free fast path for filtered messages