Performance¶
Logust is fast by default: records are formatted and written in Rust, and you don't have to do anything to get that. 🚀
But if logging is on a really hot path, it helps to know where the time goes, and the few knobs you can turn.
Caller information is the expensive part¶
To know the module, function and line of a log call, Logust has to inspect the Python call stack. That's the most expensive part of a log call. The same goes, to a lesser extent, for the thread and the process.
So Logust only collects them when they are needed. When you add a handler, it reads the format and checks which fields it uses. Let's measure it:
import time
from logust import logger
logger.remove()
FORMATS = {
"without caller": "{time} | {level} - {message}",
"with caller": "{time} | {level} | {name}:{function}:{line} - {message}",
}
for label, fmt in FORMATS.items():
handler_id = logger.add("app.log", format=fmt)
start = time.perf_counter()
for i in range(100_000):
logger.info("Processed item {}", i)
elapsed = time.perf_counter() - start
logger.remove(handler_id)
print(f"{label:<15} {elapsed / 100_000 * 1e6:.2f} µs per message")
The only difference is {name}:{function}:{line} in the format. Without it, Logust doesn't look at the call stack at all.
This works for every kind of sink: files, the console, and callable sinks. For a callable sink, logger.add(fn, format="{time} | {level} - {message}") doesn't collect caller information either.
Info
The information is collected once per message, and shared by all the handlers. So if one handler needs the caller, every handler pays for it. To keep the fast path, all of your handlers need to skip the caller fields.
Filter functions (filter=) and callbacks receive the full record, so a handler with a filter function, or a callback, also makes Logust collect everything. A string or dict filter only needs the module name, so it only turns on the caller lookup.
CollectOptions¶
The automatic detection is right most of the time. If you want to decide yourself, pass a CollectOptions to logger.add(collect=...).
It has three fields, caller, thread and process, and each one can be:
| Value | Meaning |
|---|---|
None (default) | Detect from the format. |
False | Never collect: the fields are empty. |
True | Always collect, even if the format doesn't use them. |
CallerInfo(...) / ThreadInfo(...) / ProcessInfo(...) | Use these fixed values, without looking anything up. |
Turn collection off¶
With False, the information is never collected, even if the format uses it:
import sys
from logust import CollectOptions, logger
logger.remove()
logger.add(
sys.stdout,
format="{name}:{function}:{line} | {thread.name} | {message}",
collect=CollectOptions(caller=False, thread=False),
)
def handle_request():
logger.info("Request handled")
handle_request()
The caller and thread fields are empty, and {line} is 0. That's useful for a shared format string, when you know that a fast handler doesn't need those fields.
Fixed values¶
You can also give the values yourself. Logust then uses them as they are, which costs nothing per message:
import sys
from logust import CallerInfo, CollectOptions, ProcessInfo, ThreadInfo, logger
logger.remove()
logger.add(
sys.stdout,
format="{name}:{function} | {thread.name} | {process.name} | {message}",
collect=CollectOptions(
caller=CallerInfo(name="billing", function="worker", line=0, file="billing.py"),
thread=ThreadInfo(name="billing-loop", id=1),
process=ProcessInfo(name="billing", id=1000),
),
)
def handle_request():
logger.info("Invoice sent")
handle_request()
That's handy for a service where every message comes from the same place, but the log format (shared with other services) expects these fields.
The constructors are:
from logust import CallerInfo, ProcessInfo, ThreadInfo
CallerInfo(name="mymodule", function="handler", line=42, file="handler.py")
ThreadInfo(name="WorkerThread", id=12345)
ProcessInfo(name="MainProcess", id=1234)
Always collect¶
True forces the collection, even if the format doesn't use the fields:
Performance tips¶
- Keep hot-path formats simple. Skip
{name},{function},{line}and{file}in formats where you don't need them, in all the handlers. That includes the default console handler: its format shows the caller, so calllogger.remove()before adding your own handlers. Only the handlers that accept a message's level count, so anERROR-only handler with{line}doesn't slow down yourINFOmessages. - Avoid filter functions and callbacks on hot paths. They need the full record, so they turn the caller lookup back on. To filter by module, use a string or dict filter: it is checked in Rust, without a Python call.
- Use
CollectOptionsto turn off what you don't need, or to provide fixed values. - Skip work for hidden messages. Use
opt(lazy=True)orlogger.is_level_enabled()to avoid computing values for messages that won't be written. - Use
enqueue=Truewhen a slow disk must not block your code (see Async Writes). It doesn't make Logust faster, it moves the I/O to another thread. - Keep the default buffering on hot paths.
buffering=1(onewrite()system call per line, like loguru) makes every line survive a kill, but the system call is most of the time of a file log call: about 2.5 µs per message instead of 0.9 µs with the default format, on an Apple Silicon Mac. Use it where losing the last lines on a kill matters more. See When it's written.
For numbers comparing Logust with loguru and the standard logging module, see Benchmarks.
Recap¶
- Looking up the caller is the most expensive part of a log call.
- Logust reads your formats and only collects what they use.
- The information is collected once per message, for all handlers, and filter functions and callbacks need everything.
CollectOptionsturns collection off, forces it on, or provides fixed values.