首页 > 解决方案 > 如何动态记录不同级别的消息?例如:logging.x("message") where x in ['warn',error',..]

问题描述

我想要一个函数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

标签: pythonlogging

解决方案


如果您乐于使用整数日志级别定义而不是文本级别定义(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

推荐阅读