更改logRecord中的levelname格式

2024-10-02 18:14:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何使用python的日志包更改logrecod中levelname的格式。在

formatter = logging.Formatter('%(levelname)-8s %(message)s')

基本上,我想将任何日志名称替换为名称的第一个字母。例如

^{pr2}$

等等


Tags: 名称messageformatterlogging格式字母levelnamepr2
2条回答

您可以使用精度字段来设置最大字段宽度:

formatter = logging.Formatter('%(levelname).1s %(message)s')

.1将字段宽度设置为最多一个字符,将级别截断为第一个字符:

^{pr2}$

参见String Formatting Operations documentation

Conversion: 's'
Meaning: String (converts any Python object using str()).
Notes: (6)

  1. [...] The precision determines the maximal number of characters used.

如果您想要完全不同的levelname,那么使用日志记录.addLevelName在

logging.addLevelName(logging.DEBUG, 'DETAILED')
logging.addLevelName(logging.INFO, 'GENERAL')

相关问题 更多 >