在Python中如何在函数入口、内部和出口进行日志记录

2024-04-27 02:54:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够使用Python日志工具在代码中进行简单而一致的日志记录。在

我能够做到以下几点:

  1. 我希望所有现有/未来的模块和函数都有“Entering…”和“Done…”日志消息。在
  2. 我不想在每个函数定义中添加相同的代码片段来定义日志参数(如下所示don't want to add everywhere)。在
  3. 我希望log.info(...)etc构造在我在项目层次结构中定义的任何函数中工作。在

什么不管用/我不知道怎么做:

  1. 我希望避免在我编写的每个现有/新模块中定义相同的@log装饰器。在
# don't want to add everywhere
FORMAT = '%(asctime)s - %(name)-20s - %(levelname)-5s - %(message)s'
LEVEL = logging.DEBUG
logging.basicConfig(format=FORMAT, level=LEVEL)
log = logging.getLogger(__name__)


我的Flask项目示例代码:

^{pr2}$
#app/views.py
from c import d  # various other imports required for the module

def logger(fn):
    from functools import wraps
    import inspect
    @wraps(fn)
    def wrapper(*args, **kwargs):
        global log
        log = logging.getLogger(inspect.stack()[1][3])
        log.info('About to run %s' % fn.__name__)

        out = apply(fn, args, kwargs)

        log.info('Done running %s' % fn.__name__)
        # Return the return value
        return out
    return wrapper

    @app.route('/this_func')
    @logger
    def this_func():
        log.info('I am doing logging without having to do bunch of definitions.')
        # some more code

    @app.route('/that_func')
    @logger
    def that_func():
        log.info('Yet more logging without having to do bunch of definitions.')
        log.info('I can simply refer to the log object and be done with it.')
        # some more code

Tags: theto函数代码nameimportinfolog
1条回答
网友
1楼 · 发布于 2024-04-27 02:54:43

最后一个对我有用的设置是:

# At the beginning of every .py file in the project
def logger(fn):
    from functools import wraps
    import inspect
    @wraps(fn)
    def wrapper(*args, **kwargs):
        log = logging.getLogger(fn.__name__)
        log.info('About to run %s' % fn.__name__)

        out = apply(fn, args, kwargs)

        log.info('Done running %s' % fn.__name__)
        # Return the return value
        return out
    return wrapper

# Do the following section only in application's app/__init__.py
# Other files will pick it up from here.
FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(funcName)s - %(message)s'

# Change logging LEVEL according to debugging needs.
# Probably better to read this from a config or a launch parameter.
LEVEL = logging.DEBUG

logging.basicConfig(format=FORMAT, level=LEVEL)
# Up to here only for app/__init__.py

# This section again at the beginning of every .py file
log = logging.getLogger(__name__)
log.info('Entered module: %s' % __name__)

{or decorator>现在在函数中添加

^{pr2}$

相关问题 更多 >