Python:截断的日志级别名称(字符串格式)自定义

NWa*_*ers 3 python logging string-formatting

我正在使用 pythons 日志模块,我想对我的日志消息进行简单的更改。这是格式化程序的样子,以及结果:

console_err_format = logging.Formatter(
    str("%(asctime)s - " + "%(levelname)s" +" - %(message)s"),
    "%H:%M:%S")

12:35:33 - INFO - Assessing reads and library type
12:35:33 - DEBUG - Checking reads...
12:35:33 - WARNING - Error while checking reads...
Run Code Online (Sandbox Code Playgroud)

我只想显示记录器级别的第一个字符:

12:35:33 - I - Assessing reads and library type
12:35:33 - D - Checking reads...
12:35:33 - W - Error while checking reads...
Run Code Online (Sandbox Code Playgroud)

有谁知道如何做到这一点?我尝试了以下事情,但无济于事:

# attempt 1
console_err_format = logging.Formatter(
    str("%(asctime)s - " +"{0}".format("%(levelname)s"[:1]) +" - %(message)s"), "%H:%M:%S")
# attempt 2
console_err_format = logging.Formatter(
    str("%(asctime)s - " +"%(levelname)s"[:1] +" - %(message)s"), "%H:%M:%S")
Run Code Online (Sandbox Code Playgroud)

任何提示将不胜感激!如果有人想出如何集成颜色记录模块之一,则加分!

Vin*_*jip 7

将格式说明符用于 1 个字符的精度,如下例所示:

>>> import logging
>>> logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname).1s %(message)s')
>>> logging.debug('Message should be as required')
2017-11-01 00:47:31,409 D Message should be as required
>>> logging.warning('Warning message should be as required')
2017-11-01 00:47:50,702 W Warning message should be as required
>>> 
Run Code Online (Sandbox Code Playgroud)

注意.1in 前面的sin 说明%(levelname)符,它将该值的输出限制为一个(第一个)字符。


Luk*_*ith 6

我不知道如何使用格式化程序来做到这一点,但您可以用您自己的字符串替换内置的关卡名称字符串。例如:

logging.addLevelName(logging.WARNING, 'W')
Run Code Online (Sandbox Code Playgroud)

将与 WARNING 级别关联的字符串替换为单个字符“W”。对所有级别重复上述操作将达到预期的效果。