美文网首页
python 带参数的装饰器

python 带参数的装饰器

作者: SkTj | 来源:发表于2019-12-04 11:06 被阅读0次

    from functools import wraps
    import logging

    def logged(level, name=None, message=None):
    """
    Add logging to a function. level is the logging
    level, name is the logger name, and message is the
    log message. If name and message aren't specified,
    they default to the function's module and name.
    """
    def decorate(func):
    logname = name if name else func.module
    log = logging.getLogger(logname)
    logmsg = message if message else func.name

        @wraps(func)
        def wrapper(*args, **kwargs):
            log.log(level, logmsg)
            return func(*args, **kwargs)
        return wrapper
    return decorate
    

    Example use

    @logged(logging.DEBUG)
    def add(x, y):
    return x + y

    @logged(logging.CRITICAL, 'example')
    def spam():
    print('Spam!'

    相关文章

      网友评论

          本文标题:python 带参数的装饰器

          本文链接:https://www.haomeiwen.com/subject/yckhpctx.html