The following Code (or Customs Solutions from 更妥善地在沙捞法中标注吗? 或使用inspect
的解决方案。
import logging, sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logger = logging.getLogger()
def log(func):
def logged(*args, **kwargs):
logger.info(f"{func.__name__} starting with {args=} {kwargs=}...")
result = func(*args, **kwargs)
logger.info(f"{func.__name__} finished.")
return result
return logged
class A:
@log
def foo(self, x, y):
pass
@log
def bar(self, x, y):
1/0
a = A()
a.foo(2, y=3)
a.bar(2, y=3)
产出:
INFO:root:foo starting with args=(<__main__.A object at 0x0000000002784EE0>, 2) kwargs={ y : 3}...
INFO:root:foo finished.
INFO:root:bar starting with args=(<__main__.A object at 0x0000000002784EE0>, 2) kwargs={ y : 3}...
...
现有沙丘版本中是否有内在解决办法(要么在logging
上,要么在另一个模块中)?