Function Timing Decorators¶
Sometimes you just want to know how long a function takes, without adding time.perf_counter() calls and a log line to each one.
logust.contrib has two decorators for that: @log_fn and @debug_fn. Put one on a function, and every call logs the function name and its elapsed time. ⏱
Time a function with @log_fn¶
import time
from logust.contrib import log_fn
@log_fn
def process_data(items):
time.sleep(0.12)
return [item * 2 for item in items]
result = process_data([1, 2, 3])
print(result)
The function works exactly as before: it gets the same arguments and returns the same value. After it returns, @log_fn logs:
- At the
INFOlevel. - The message
Called <function name> with elapsed_time=<seconds>, with the seconds rounded to 3 decimals.
Notice the caller in the log: __main__:<module>:12. It's the line that called process_data(), not a line inside the decorator. That's usually what you want to see.
Info
The elapsed time is only in the message text. It is not added as an extra field.
Async functions¶
Both decorators detect async def functions and time the whole await. Here with @debug_fn, which logs at the DEBUG level:
import asyncio
from logust.contrib import debug_fn
@debug_fn
async def fetch_user(user_id):
await asyncio.sleep(0.05)
return {"id": user_id, "name": "Alice"}
async def main():
user = await fetch_user(123)
print(user)
asyncio.run(main())
Detailed timings with @debug_fn¶
Use @debug_fn for small, frequent functions. Their timings are useful when you investigate a problem, but noise the rest of the time.
They only show up when the DEBUG level is enabled. Here the console level is set to INFO, so only the outer function is logged:
from logust import logger
from logust.contrib import debug_fn, log_fn
@debug_fn
def parse_row(row):
return row.split(",")
@log_fn
def import_file(rows):
return [parse_row(row) for row in rows]
logger.set_level("INFO")
import_file(["a,b", "c,d"])
Tip
The default console level of Logust is DEBUG, so @debug_fn timings are shown until you raise the level. Read more in Log Levels.
Choose the level¶
@log_fn also accepts a level. Use it with parentheses, @log_fn(level=...):
import time
from logust import logger
from logust.contrib import log_fn
logger.level("TIMING", no=15, color="magenta", icon="⏱")
@log_fn(level="WARNING")
def slow_operation():
time.sleep(0.2)
@log_fn(level="TIMING")
def quick_operation():
return 42
slow_operation()
quick_operation()
The level can be any built-in level name, or a custom level you registered, like TIMING here. A dedicated level is handy: you can then send timings to their own file, or filter them out, by level.
@debug_fn is the same as @log_fn(level="DEBUG"), and doesn't take a level.
When the function raises¶
The time is logged after the function returns. If it raises an exception, nothing is logged and the exception propagates as usual:
from logust.contrib import log_fn
@log_fn
def divide(a, b):
return a / b
divide(10, 2)
try:
divide(1, 0)
except ZeroDivisionError:
print("divide() raised, and no timing line was logged")
If you also want the error in your logs, combine it with @logger.catch.
Recap¶
@log_fnlogsCalled <name> with elapsed_time=<seconds>atINFOafter each call.@debug_fndoes the same atDEBUG.@log_fn(level="...")uses any level, including custom ones.- Both work with sync and
async deffunctions, and report the caller's location. - Nothing is logged when the function raises.