python - 如何简化Python日志代码

标签 python logging wrapper

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

@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()) 

最佳答案

您可以使用 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

关于python - 如何简化Python日志代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28900454/

相关文章:

java - 保存字段标记为可更新 = false 的实体时,禁用警告 "entity was modified, but it won' t be update because the property is immutable

.net - 从 C# 调用 Fortran dll 函数的堆栈溢出异常

c array wrapper struct 不允许 malloc

python - python 中的事件处理程序,类似于 C# 吗?监听串行消息

python - 如何在 django 翻译中保留内联链接?

python - 将数据文件添加到python项目setup.py

MySQL如何将字符串附加到磁盘上的外部文件?

c# - 并发文件写入

python - 一个*完美*的 Python 调试器应该具备哪些特性?

c# - 从 C# 运行 C++ Qt 应用程序