Python:当控件进入内部/外部函数时自动调试日志

时间:2016-03-01 05:37:51

标签: python debugging logging

我正在尝试一个具有许多功能的项目。我正在使用标准logging模块要求是记录说明

的DEBUG日志
<timestamp> DEBUG entered foo() 
<timestamp> DEBUG exited foo()
<timestamp> DEBUG entered bar()
<timestamp> DEBUG exited bar()

但我不想在每个函数中编写DEBUG日志。在Python中是否有一种方法可以处理包含函数入口和出口的自动日志?
我不想对所有函数使用任何decorator,除非它是Python中唯一的解决方案。

提前致谢

2 个答案:

答案 0 :(得分:2)

你有什么理由不想使用装饰器吗?这很简单:

from functools import wraps
import logging

logging.basicConfig(filename='some_logfile.log', level=logging.DEBUG)

def tracelog(func):

    @wraps(func) # to preserve docstring
    def inner(*args, **kwargs):
        logging.debug('entered {0}, called with args={1}, kwargs={2}'.format(func.func_name, *args, **kwargs))
        func(*args, **kwargs)
        logging.debug('exited {0}'.format(func.func_name))

    return inner

如果你这样做,那么传入一个独立的记录器只是另一层:

def tracelog(log):

    def real_decorator(func):
        @wraps(func)
        def inner(*args, **kwargs):
            log.debug('entered {0} called with args={1}, kwargs={2}'.format(func.func_name, *args, **kwargs))
            func(*args, **kwargs)
            log.debug('exited {0}'.format(func.func_name))
        return inner
    return real_decorator

很酷的是,这适用于功能和方法

用法示例:

@tracelog(logger)
def somefunc():
    print('running somefunc')

答案 1 :(得分:0)

您想查看sys.settrace

对于呼叫跟踪的代码示例,有一个很好的解释:https://pymotw.com/2/sys/tracing.html

这是一种非常原始的方法,请查看更多有用示例的链接:

import sys
def trace_calls(frame, event, arg):
    if event not in ('call', 'return'):
       return
    co = frame.f_code
    func_name = co.co_name
    if func_name == 'write':
       # Ignore write() calls from print statements
       return
    if event == 'call':
       print "ENTER: %s" % func_name
    else:
       print "EXIT: %s" % func_name

 sys.settrace(trace_calls)