如何在python日志记录模块中获取当前日志级别

wah*_*wah 3 python logging python-2.7

我正在尝试创建一个基本的记录器,该记录器无需外部包装即可上色,

# these have to be the first functions so I can use it in the logger settings
def create_log_name(log_path="{}/log", filename="zeus-log-{}.log"):
    if not os.path.exists(log_path.format(os.getcwd())):
        os.mkdir(log_path.format(os.getcwd()))
    find_file_amount = len(os.listdir(log_path.format(os.getcwd())))
    full_log_path = "{}/{}".format(log_path.format(os.getcwd()), filename.format(find_file_amount + 1))
    return full_log_path


def set_color_value(levelname):
    log_set = {
        "INFO": "\033[92m{}\033[0m",
        "WARNING": "\033[93m{}\033[0m",
        "DEBUG": "\033[94m{}\033[0m",
        "ERROR": "\033[91m{}\033[0m",
        "CRITICAL": "\033[91m{}\033[0m"
    }
    return log_set[levelname].format(levelname)

logger = logging.getLogger("zeus-log")
logger.setLevel(logging.DEBUG)
file_handler = logging.FileHandler(
    filename=create_log_name(), mode="a+"
)
file_handler.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
file_format = logging.Formatter(
    '%(asctime)s;%(name)s;%(levelname)s;%(message)s'
)
console_format = logging.Formatter(
    "[%(asctime)s {}] %(message)s".format(set_color_value()), "%H:%M:%S"
)
file_handler.setFormatter(file_format)
console_handler.setFormatter(console_format)
logger.addHandler(console_handler)
logger.addHandler(file_handler)
Run Code Online (Sandbox Code Playgroud)

因此,到目前为止,我需要做的就是获取将在中设置的当前日志级别,并将其logging.Formatter发送到我的小功能:

console_format = logging.Formatter(
    "[%(asctime)s {}] %(message)s".format(set_color_value()), "%H:%M:%S"
)
Run Code Online (Sandbox Code Playgroud)

是否可以从日志记录包中获取当前日志级别?


例如,可以说我通过了,logger.INFO("test")我需要一种方法来INFO从字符串中获取该部分,并从那里set_color_value("INFO")返回:

在此处输入图片说明

bca*_*tle 28

如果您正在使用根记录器,例如因为您调用了,logging.basicConfig()那么您可以使用

import logging
logging.root.level
Run Code Online (Sandbox Code Playgroud)

例如

if logging.DEBUG >= logging.root.level:
    # Do something
Run Code Online (Sandbox Code Playgroud)

  • 最好使用 `isEnabledFor()` 函数而不是显式比较。请参阅此处:https://docs.python.org/3/howto/logging.html#optimization (2认同)

Mil*_*lyi 24

是的,您可以通过以下方式检查记录器级别

level = logger.level
Run Code Online (Sandbox Code Playgroud)

  • 这个答案回答了问题提出的问题。自从我来到这里寻找这个答案以来,您的问题需要改进。 (3认同)
  • 无论我将其设置为`INFO` 还是`DEBUG`,例如像这样`logging.basicConfig(stream=sys.stdout, level='DEBUG')`,logger.level 总是显示0,没有帮助。@CecilCurry “_oddly_ 非正交”是什么意思?在[正交性的这个定义](http://www.catb.org/~esr/writings/taoup/html/ch04s02.html#orthogonality)的背景下,我不确定 (3认同)
  • 这不是只显示当前记录器设置的级别吗?我需要一种方法来从记录器传递的每个字符串中获取日志信息,例如,假设我传递了 `logger.FATAL("test")` 我需要将 `FATAL` 部分作为字符串传递 (2认同)
  • **同意。**您问题的内容与您的问题标题@wahwahwah 不一致。StackOverflowers(包括我自己)可能对后者更感兴趣。奇怪的是,`logging` API 定义了`setLevel()` 和`getEffectiveLevel()` 方法,但*没有* `getLevel()` 方法,当他们可以简单地定义一个简单的`getLevel(self ): 返回 self.level` 方法。`</sigh>` (2认同)
  • @CecilCurry 支持你的意见。`logging` 的文档页面没有提到可以通过 logger 对象直接访问 `level`。它只提到“getEffectiveLevel”作为获取当前日志级别的方法。找不到其他任何东西可以达到同样的目的。 (2认同)

小智 23

正如本次演练中所解释的,源代码 logger.level通常是错误的。

\n

你要logger.getEffectiveLevel()

\n

引用来源:

\n
\n

这里\xe2\x80\x99s 的要点是:不要\xe2\x80\x99t 依赖于.level. 如果您尚未在记录器对象上显式设置级别,并且您出于.level某种原因依赖于记录器对象,那么您的日志记录设置的行为可能与您预期的不同。

\n
\n


wah*_*wah 5

我决定以其他方式执行此操作,并在字符串本身中添加带有级别编号的颜色:

def set_color(org_string, level=None):
    color_levels = {
        10: "\033[36m{}\033[0m",       # DEBUG
        20: "\033[32m{}\033[0m",       # INFO
        30: "\033[33m{}\033[0m",       # WARNING
        40: "\033[31m{}\033[0m",       # ERROR
        50: "\033[7;31;31m{}\033[0m"   # FATAL/CRITICAL/EXCEPTION
    }
    if level is None:
        return color_levels[20].format(org_string)
    else:
        return color_levels[int(level)].format(org_string)
Run Code Online (Sandbox Code Playgroud)

因此,例如:

logger.info(set_color("test"))
logger.debug(set_color("test", level=10))
logger.warning(set_color("test", level=30))
logger.error(set_color("test", level=40))
logger.fatal(set_color("test", level=50))
Run Code Online (Sandbox Code Playgroud)

将输出:

在此处输入图片说明


Jua*_*rgo 5

在您的记录器实例中,您可以像这样检查它,正如@Milán Vásárhelyi 所说:

myLogger.level

这会将级别返回为 int。如果您更喜欢将名称显示为字符串,您可以执行以下操作:

logging.getLevelName(myLogger.level)