Migrate from loguru¶
Logust follows the loguru API, so for most code, migrating is changing one import.
This page lists what stays the same, and the small differences you may hit when you port a bigger loguru setup.
Change the import¶
logger.add() and its common options (level, format, filter, rotation, retention, compression, serialize, enqueue, colorize, backtrace, diagnose, catch), bind(), contextualize(), patch(), opt(), catch(), level(), configure(), enable() / disable(), complete() and parse() work the way you know. The default handler is the same too: it writes to sys.stderr, from DEBUG up, with colors only when loguru would use them (a terminal, NO_COLOR, FORCE_COLOR, CI, PyCharm, Jupyter).
The rest of this page goes through the differences, by topic.
Keyword arguments and extra¶
logger.info("{} by {user}", "login", user="alice") formats the message the same way in both libraries.
The difference is in extra. loguru copies every keyword argument into extra. Logust only adds the ones that are not used by a placeholder in the message:
import sys
from logust import logger
logger.remove()
logger.add(sys.stderr, format="{message} | extra={extra}")
logger.info("{} by {user}", "login", user="alice", ip="10.0.0.7")
logger.bind(user="alice").info("{} by {user}", "login", user="alice")
If you want a value both in the message and in extra, bind() it, as in the second call.
opt(capture=False) keeps every keyword argument out of extra, in both libraries. Read more in Message Arguments.
contextualize()¶
contextualize() is context-local in both libraries: the values live in a contextvars variable, so each thread and asyncio task sees only its own blocks. The precedence is the same too: contextualize() values, then bind() values, then the message's keyword arguments, later sources winning. See Adding Context.
There are a few small differences:
- Logust's
contextualize()yields the logger, sowith logger.contextualize(...) as log:works. loguru's yieldsNone. configure(extra=...)binds the values to the logger in Logust, so they overridecontextualize()values with the same key, likebind()does. In loguru they are the core defaults, andcontextualize()overrides them.- A block entered in one
contextvarscontext and exited in another (for example, an async generator closed by another task) restores the previous values, instead of raisingValueErroras loguru does.
Callable sinks receive no trailing newline¶
loguru passes callable sinks the formatted message with a trailing "\n", so loguru recipes often use end="". Logust passes it without one, so drop end="" when you port them:
If you keep end="" with Logust, all your log lines are joined into one (see Progress Bars).
Stream sinks (objects with a write() method, like sys.stdout or io.StringIO) get a trailing newline in both libraries.
Also, a loguru callable sink gets a str subclass with a .record attribute. A Logust callable sink gets a plain str. If you need the record, use add_callback().
Format strings¶
loguru format strings work as they are, including {time:YYYY-MM-DD}, {level.icon}, {thread.name}, {file.path} and Python format specs such as loguru's default {level: <8}, {line:05d} or {message:>20} (see Format tokens and Format specs). The differences:
{exception}places the traceback once, where you put it. loguru appends"\n{exception}"to every string format, so a loguru format that contains{exception}prints it twice.- Plain
{time}gives2026-10-06 12:00:00.123on the console and in files (loguru: ISO 8601). Use{time:}for ISO 8601. In callable sinks, plain{time}gives ISO 8601 with microseconds. {thread}and{process}givename:id, likeMainThread:8348778368(loguru: the id). Use{thread.id}/{process.id}for the id.- The
zztime token gives the UTC offset (+09:00) instead of a time zone abbreviation, except with!UTC. {extra[key]:<spec>}formats the value's text,str(value): string specs like{extra[user]:<8}work, but{extra[count]:05d}writes42unformatted (loguru:00042).- An invalid format spec, like
{message:d}, raisesValueErrorinlogger.add(). loguru raises it later, when a message is logged. {extra}sorts the keys (loguru keeps the binding order), and writes values other thanstr, numbers,bool,None, lists, tuples and dicts withstr()instead ofrepr().
Exceptions¶
backtraceanddiagnose:add()accepts both, as in loguru, but both areFalseby default. loguru defaults toTrue, which writes variable values (possibly secrets 🚨) into your logs. Pass them explicitly if you want loguru's level of detail. See Tracebacks.- Traceback style:
diagnose=Truelists the variables used on each line as| name = value, instead of loguru's annotated source lines.backtrace=Trueadds the outer frames without loguru's⥤marker. Tracebacks are not colorized. opt(backtrace=True)andopt(diagnose=True)are Logust additions: they turn the detail on for one message, on every handler.
Message markup and opt()¶
opt(colors=...): loguru parses color markup in a message only withopt(colors=True). Logust always parses it (and strips it on sinks without colors), socolors=Truechanges nothing, andcolors=Falsekeeps the tags as plain text for that message.opt(capture=False)works as in loguru.opt(raw=True)andopt(record=True)are not supported yet: they raiseTypeError.
Read more in Per-message Options with opt().
Record dicts in filters, patchers, and callbacks¶
Filters, patchers and add_callback() callbacks get a record with loguru's keys: record["level"].no, record["time"] (an aware datetime), record["elapsed"] (a timedelta), record["file"].path, record["thread"].id, record["process"].name, record["module"], and so on. See The record dict.
The differences:
record["exception"]is the traceback text, orNone. It's not a(type, value, traceback)tuple.record["level"]andrecord["file"]are also strings:record["level"] == "INFO"is true. The record also keeps Logust's flat keys (level_no,timestamp,thread_id, ...).- A patcher's record has no caller fields (
name,module,function,line,file), and only its changes tomessage,extraandexceptionare used. - The values in
record["extra"]are strings: loguru keeps the original objects.
Let's see the last one:
from logust import logger
logger.remove()
logger.add_callback(lambda record: print(repr(record["extra"])))
logger.bind(order_id=1234, total=9.99, tags=["new"]).info("Order placed")
So a filter like record["extra"]["order_id"] > 1000 needs an int(...) with Logust. The values keep their types in JSON output.
File sink options¶
compression, mode, encoding, delay and catch use loguru's names, with these differences:
compression:"gz","bz2","zip","tar","tar.gz"and"tar.bz2"are supported, andTruemeans gzip."xz","lzma"and"tar.xz"raiseValueError. A compression function raisesTypeError.mode: only"a"and"w"are supported. Others raiseValueError.encoding: files are always written as UTF-8. UTF-8 aliases are accepted; other encodings raiseValueError.catch: loguru defaults tocatch=True, which prints sink errors to stderr. Logust defaults tocatch=None, which drops them silently. Passcatch=Truefor loguru's behavior, orcatch=Falseto raise the error from the logging call. See Sink Errors.- Rotated file names follow Logust's
app.<timestamp>.pid<pid>.logpattern, with the archive extension appended (for example.log.zip). See Rotated file names. bufferingis passed toopen()in loguru, and has the same meaning in Logust, but a different default: loguru writes each line before the logging call returns (buffering=1), Logust keeps an 8 KB buffer, written when full, bycomplete(),remove()and at normal exit. A process killed by a signal loses what's still buffered; passbuffering=1to get loguru's behavior.buffering=Nkeeps up toNbytes in memory, andbuffering=0raisesValueError, asopen()does for a text file. The otheropen()arguments (newline,errors,opener...) are not supported: they raiseTypeError.- Time-based
rotation:timedelta(days=1),timedelta(hours=1)andtime(0, 0)are supported, and rotate on clock boundaries (midnight, top of the hour, local time, daylight saving changes handled like loguru). Other intervals and times raiseValueError. rotationandretentionstrings: sizes ("500 MB"),"daily"/"1 day"and"hourly"/"1 hour"for rotation, and a number of days ("10 days") for retention. loguru also accepts values like"1 week","monday at 12:00","2 months"or functions; in Logust, unsupported strings raiseValueErrorwhen you calladd(). See All rotation values.
mode, encoding and delay only apply to file sinks; passing them for another sink raises TypeError.
Other differences¶
catch(): same call shapes as loguru (@logger.catch,@logger.catch(...),with logger.catch():) and the sameexception,level,reraise,onerror,excludeanddefaultoptions. The message is"An error occurred: <exception>"(change the prefix withmessage=), not loguru's"An error has been caught in function ...".level(): returnsLevel(name, no, color, icon)like loguru, butcoloris a color name ("green") rather than markup ("<green><bold>"). Level names are case-insensitive. Passing a newnofor an existing custom level re-registers it instead of raising; for a built-in level it raisesTypeError, as in loguru.filter: strings (filter="mypkg"), dicts (filter={"": "WARNING", "mypkg": "DEBUG"}) and callables work as in loguru, and are validated the same way when you calladd(). String and dict filters are checked in Rust, without a Python call per message. A filter that raises drops the record as in loguru; with Logust's defaultcatch=Nonethe error is not reported (passcatch=Truefor loguru's report). See Filtering Records.- Coroutine sinks:
async defsinks are not supported yet.add()raisesTypeErrorinstead of silently never awaiting them. enable()/disable():enable("mylib")anddisable("mylib")follow loguru (prefix match on the dotted module name, most specific rule wins,""means all modules). Without a name, or with a built-in level name such asenable("INFO"), they keep Logust's meaning: they switch the console handlers (the default one and yoursys.stdout/sys.stderrones) off and back on. loguru has no such form. Records fromInterceptHandlerare matched against thelogginglogger name. See Logging in Libraries.logger.parse(): the same aslogust.parse(). It takes a file path (not an open file), andcastmust be a dict. See Parsing Logs.
Recap¶
- Change
from loguru import loggertofrom logust import logger; the common API is the same. - Keyword arguments used by the message don't go to
extra;bind()them if you need both. - Drop
end=""in callable sinks. backtraceanddiagnoseare off by default; turn them on explicitly.- Message markup is always parsed;
opt(raw=...)andopt(record=...)are not available. record["exception"]is text, andrecord["extra"]values are strings in filters, patchers and callbacks.contextualize()is context-local as in loguru, but yields the logger, andconfigure(extra=...)values win over it.- Some file options have a smaller set of values: no
xzcompression,"a"/"w"modes only, UTF-8 only, and fewerrotation/retentionstrings (others raiseValueError).