【问题标题】:How to generate values from my business logic to the log file using decorators?如何使用装饰器从我的业务逻辑生成值到日志文件?
【发布时间】:2018-12-26 11:47:30
【问题描述】:

我想从日志文件中的业务逻辑生成值,但我不知道如何去做。

import time
import logging

logging.basicConfig(filename='new_example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
logging.error('Please check')

def log_check(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        logging.info(func.__name__ + "took" + str ((end - start) * 1000) + "mili seconds")
        #logging.info('this is what {}'.format(func.__name__)+ func["user"] + " : " + func["passw"])
        print (func.__name__ + "took" + str ((end - start) * 1000) + "mili seconds")
        return result
    return wrapper()

@log_check
def login():
    user = raw_input("Username: ")
    passw = raw_input("Password: ")
    return {"user":user, "passw":passw}

我希望在日志文件中生成我为用户和密码提供的值。 我怎么做? 我将INFO:root:logintook1964.99991417mili seconds 作为我的日志文件中的记录,但我希望我作为用户和密码输入的值也随之生成。

【问题讨论】:

    标签: python decorator aop python-decorators


    【解决方案1】:

    您应该使用result["user"]result["passw"] 而不是func["user"]func["passw"],因为值在函数的返回值中,而不是在函数本身中:

    def log_check(func):
        def wrapper(*args, **kwargs):
            start = time.time()
            result = func(*args, **kwargs)
            end = time.time()
            logging.info(func.__name__ + "took" + str ((end - start) * 1000) + "mili seconds")
            logging.info('this is what {}'.format(func.__name__)+ result["user"] + " : " + result["passw"])
            print (func.__name__ + "took" + str ((end - start) * 1000) + "mili seconds")
            return result
        return wrapper()
    

    【讨论】:

    • 这仅适用于login 函数——在任何不返回带有“user”和“passwd”键的dict的东西上使用这个装饰器,它会崩溃。使装饰器的使用变得毫无用处,不是吗?
    【解决方案2】:

    如果通用装饰器假设任何关于装饰函数返回值的内容,您就不能让其工作 - 您在这里所能做的就是记录结果(无论它是什么),即:

    def log_check(func):
        def wrapper(*args, **kwargs):
            start = time.time()
            result = func(*args, **kwargs)
            end = time.time()
            # proper use of `logger` methods: dont build the whole string, just 
            # pass a format string and the matching arguments)
            logging.info("%s took %s milliseconds", func.__name__,  (end - start) * 1000)
            # if you hope to use this decorator on anything else than
            # your login function, don't assume _anything_ about what
            # the decorated func might return
            logging.info('func %s returned %s', func.__name__, result)
            return result
    
    
        # You want to return the wrapper function, not
        # to call it !!!
        # return wrapper()
        return wrapper
    

    话虽如此,您不应将不相关的问题混为一谈,即利用数据(计时函数执行)和特定领域的数据(函数返回的内容等)。我会亲自从函数本身内部进行特定于域的日志记录。我会从不记录敏感数据,例如用户名/密码对(如果您有泄露此类信息的习惯,请提醒我永远不要使用您的任何程序)。

    【讨论】:

      猜你喜欢
      • 2021-04-27
      • 1970-01-01
      • 2011-10-17
      • 2015-11-07
      • 1970-01-01
      • 2021-05-03
      • 2010-12-20
      • 1970-01-01
      • 2012-10-22
      相关资源
      最近更新 更多