Skip to content

Commit

Permalink
ADD extra_info parameter to Logger.benchmark
Browse files Browse the repository at this point in the history
  • Loading branch information
mkrd committed Oct 5, 2022
1 parent 6fe2df5 commit 0ceaf01
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 8 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "super-py"
version = "1.0.1"
version = "1.0.2"
repository = "https://github.com/mkrd/SuperPy"
description = "Features that Python should have in the standard library"
authors = ["Marcel Kröker <kroeker.marcel@gmail.com>"]
Expand Down
32 changes: 28 additions & 4 deletions super_py/logging.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import time
import logging
import functools
from logging.handlers import RotatingFileHandler
from typing import Callable, Union

from . import string

Expand Down Expand Up @@ -69,7 +69,8 @@ def benchmark(
_func=None,
*,
with_args: list[int] = [],
with_kwargs: list[str] = []
with_kwargs: list[str] = [],
extra_info: Union[Callable, list[Callable]] = None,
):
"""
A function decorator for the logger that logs the time it takes to execute a function
Expand All @@ -88,6 +89,21 @@ def my_func(a, b, c=None, d=None):
:param with_args: a list of indices of the arguments to be logged
:param with_kwargs: a list of keyword arguments to include in the log
:param extra_info: a function or list of functions that return extra information to be logged, separated by dashes
Use the `extra_info` parameter like so:
@log.benchmark(extra_info=[lambda: current_user.name, lambda: time.time()])
def my_func():
...
or only pass a single function:
@log.benchmark(extra_info=lambda: current_user.name)
def my_func():
...
:return: A decorator.
"""
# The decorator is called or returned at the end depending on whether
Expand All @@ -102,13 +118,21 @@ def wrapper(*args, **kwargs):
res = func(*args, **kwargs)
t2 = time.time()

# Create log message
# Create log message with args and kwargs of function
ms = f"{(t2 - t1) * 1000:.1f}ms".rjust(9)
arglist = [f"{a}" for i, a in enumerate(args) if i in with_args]
kwarglist = [f"{k}={a}" for k, a in kwargs.items() if k in with_kwargs]
arg_str = ", ".join(arglist + kwarglist)
log = f"{ms} {func.__name__}({arg_str})"

# Add extra info
if isinstance(extra_info, list):
for info_fn in extra_info:
log += f" - {info_fn()}"
elif extra_info is not None:
log += f" - {extra_info()}"
self.logger.debug(log)

self.logger.debug(f"{ms} {func.__name__}({arg_str})")
return res
return wrapper
return decorator if _func is None else decorator(_func)
11 changes: 8 additions & 3 deletions tests/test_logger.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@


from curses.ascii import US
import imp
import super_py as sp
import time


class User:
def __init__(self, name):
self.name = name


log = sp.logging.Logger("main", files=["main.log"], ts_color="bright_green")
log_combined = sp.logging.Logger("combined", files=["combined.log"], ts_color="bright_orange")


log("hi")
user = User("John Doe")


@log_combined.benchmark(with_args=[0], with_kwargs=["a"])
@log.benchmark(with_args=[0, 1], with_kwargs=["three", "four"])
@log.benchmark(with_args=[0, 1], with_kwargs=["three", "four"], extra_info=[lambda: user.name, lambda: time.time()])
def wait_500ms(one, two, *, three, four):
time.sleep(one)
return "done"


print(wait_500ms(1.3, 20, three=30, four=40))
user.name = "Jane Doe"
print(wait_500ms(0.01, 20, three=30, four=40))

0 comments on commit 0ceaf01

Please sign in to comment.