我想要一个函数def log(message, level): logging.level("message")
,而不是编写logging.error("message")
,我只想将此函数称为log(“ message”,error)。这是代码。
import logging
def logging_exception(message, level):
raise Exception(message)
logging.level(message)
logging_exception("this is an error",error)
预期结果:error message : this is an error
答案 0 :(得分:1)
如果您乐意使用整数记录级别定义而不是文本(https://docs.python.org/3/library/logging.html#logging-levels),则可以使用log方法代替单个级别方法
import logging
logging.log(50,"This is a critical log message")
输出:
CRITICAL:root:This is a critical log message
答案 1 :(得分:0)
我以这种方式解决了问题,欢迎新想法!
import logging
def logging_exception(message, level):
str = 'logging.'+level+'('+"message"+')'
exec(str)
raise Exception(message)
logging_exception("this is an error",'error')
答案 2 :(得分:0)
您可以通过简单地定义一个dict
(包含要调用的所有名称),然后将值传递给dict来检索所需的日志记录级别,从而以一种非常直接的方式实现此目的。
import logging
global __logger_methods
__logger_methods = {
logging.DEBUG: logging.debug,
"debug": logging.debug,
logging.INFO: logging.info,
"info": logging.info,
logging.WARNING: logging.warning,
"warning": logging.warning,
logging.WARN: logging.warn,
"warn": logging.warn,
logging.ERROR: logging.error,
"error": logging.error,
logging.CRITICAL: logging.critical,
"critical": logging.critical
}
def logging_exception(message, level):
global __logger_methods
if level in __logger_methods.keys():
__logger_methods[level](message)
else:
logging.error("Unknown Logging Level {} for message `{}`".format(level, message))
raise Exception(message)
logging_exception("this is an error", logging.ERROR)
最后一行产生以下输出:
ERROR:root:this is an error
Traceback (most recent call last):
File "C:\Program Files\Python37\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Program Files\Python37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File ".\__main__.py", line 24, in <module>
logging_exception("this is an error", logging.ERROR)
File ".\__main__.py", line 21, in logging_exception
raise Exception(message)
Exception: this is an error
答案 3 :(得分:0)
我的最终代码正在这样工作。感谢所有贡献者。
导入日志记录
def logging_exception(消息,级别):
level_code = getattr(logging,level.upper())
logger.log(level_code,message)
raise Exception(message)
logging_exception(“错误消息”,“错误”)