[英]get the inbuilt function's method name which is passed as an argument and call inside function body
I'm looking to generalize the logging activity in python in my work. 我希望在我的工作中概括python中的日志记录活动。
Rather than calling logger.debug(), logger.info(), logger.warning() etc, I'm thinking of writing a template function which get all the necessary arguments to call either debug , info or warning etc. 我正在考虑编写一个模板函数,而不是调用logger.debug(),logger.info(),logger.warning()等,该模板函数获取所有必需的参数以调用debug,info或warning等。
Example: 例:
def logging_template(logger_name, level, message):
logger = logging.getLogger(logger_name)
logger.##level(message) //Here if level is passed as debug then logger.debug should be called. If level is passed as info then logger.info should be called.
Similarly if warning or error or critical is passed then corresponding logger calls should be triggered.
I'm not interested on IF-ELSE block or condition checks. 我对IF-ELSE阻止或条件检查不感兴趣。 ##level should be replaced by the argument i'm passing.
## level应该替换为我传递的参数。
Use getattr, for example: 使用getattr,例如:
def logging_template(logger_name, level, message):
logger = logging.getLogger(logger_name)
getattr(logger, level)(message)
Explanation: 说明:
getattr(logger, level) returns the function logger.debug if level is the string "debug". 如果level是字符串“ debug”,则getattr(logger,level)返回函数logger.debug。 It returns logger.error if level is the string "error", and so on.
如果level是字符串“ error”,则返回logger.error,以此类推。
Why don't you just use the logger.log
method? 您为什么不只使用
logger.log
方法? It takes a variable level and would seem to do the same as you're trying to do here. 它需要一个可变的级别,并且似乎与您在此处尝试执行的操作相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.