【问题标题】:How to simplify python logging code如何简化python日志代码
【发布时间】:2015-03-06 14:03:55
【问题描述】:

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

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

【问题讨论】:

    标签: python logging wrapper


    【解决方案1】:

    您可以使用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() 将记录:

    启动任务 SRV_DEV

    结束任务 SRV_DEV

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      • 2018-06-12
      • 2011-05-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-25
      • 2022-01-06
      相关资源
      最近更新 更多