简体   繁体   English

获取内置函数的方法名称,该方法名称作为参数传递并在函数体内调用

[英]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.

相关问题 获取作为参数传递给父函数的函数名称 - get name of function passed as argument to parent function 调用在类内的列表内传递的函数 - Call a function passed inside a list which is inside a class Python C API:使用引用传递的参数调用Python函数 - Python C API: Call a Python function with argument(s) passed by reference 获取传递给 mock_open 的参数并为模拟调用不同的函数 - Get the argument passed to mock_open and call a different function for mock 覆盖在另一个函数内进行的函数调用的参数 - Overriding argument(s) of a function call which is made within another function 将参数传递给函数,该参数必须作为参数传递给python中的另一个函数 - Passing an argument to the function , which has to be passed as an argument to another function in python Python 调用 function 作为参数传递给 object - Python call function passed as argument on object 修改在 function 中作为参数传递的变量 - Modifying a variable passed as an argument inside a function 如何从通过另一个 function (带参数)作为参数的 function 返回一个值? 我得到一个类型错误 - How to return a value from a function which was passed another function (with arguments) as an argument? I get a TypeError 将方法名称作为函数参数传递 - Passing method name as function argument
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM