如何简化python日志记录

2024-04-26 04:17:50 发布

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

我想记录any函数的开始/结束-如何将代码简化为包装器或其他东西?你知道吗

@task()
def srv_dev(destination=development):
    logging.info("Start task " + str(inspect.stack()[0][3]).upper())
    configure(file_server, destination)
    logging.info("End task " + str(inspect.stack()[0][3]).upper()) 

Tags: 函数代码devinfotaskstackloggingdef
1条回答
网友
1楼 · 发布于 2024-04-26 04:17:50

您可以使用decorator(您已经通过@task()做了什么)。这里有一个装饰器,它以大写字母记录任何函数的开头和结尾的名称:

import logging
import inspect
import functools

def log_begin_end(func):
    """This is a decorator that logs the name of `func` (in capital letters).

    The name is logged at the beginning and end of the function execution.

    """
    @functools.wraps(func)
    def new_func(*args, **kwargs):

        logging.info("Start task " + func.__name__.upper())
        result = func(*args, **kwargs)
        logging.info("End task " + func.__name__.upper())
        return result

    return new_func

用法如下:

@log_begin_end
def myfunc(x,y,z):
    pass  # or do whatever you want

当然,你可以级联装饰器。因此,您可以使用:

@task()
@log_begin_end
def srv_dev(destination=development):
    configure(file_server, destination)

现在调用srv_dev()将记录:

Start task SRV_DEV

End task SRV_DEV

相关问题 更多 >

    热门问题