python - 更改 logRecord 中的 levelname 格式

标签 python logging

我想知道如何使用 python 的日志包更改 logRecoed 中级别名称的格式。

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

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

INFO -> I, 
WARNING -> W, 
ERROR -> E, 

等等

最佳答案

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

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

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

>>> for level in ('CRITICAL', 'ERROR', 'INFO', 'WARNING', 'DEBUG'):
...     print '%(level)-.1s %(message)s' % {'level': level, 'message': 'Hello world!'}
... 
C Hello world!
E Hello world!
I Hello world!
W Hello world!
D Hello world!

参见 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.

关于python - 更改 logRecord 中的 levelname 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27453056/

相关文章:

javascript - 如何使用 Flask 和 jquery 解决这个问题? HTTP400 : BAD REQUEST - The request could not be processed by the server due to invalid syntax

python - 在多个工作人员的支持下,在 gensim 中批量训练 word2vec

python - 类型错误 : function() takes exactly 2 arguments (1 given) (python)

python - 如何动态地将变量传递给自定义 python 日志记录类中的类 __init__ 方法

grails - 在Grails 3.2.8中尚未通过logback.groovy文件配置Log4j

python - 日志记录模块不写入文件

javascript - python socket - 无法从javascript获取发送的数据

python - openssl hmac 与 python hmac 不同

java - 从 log4j 转换后的 Logback 模式异常

testing - 基于 leiningen 测试元数据的 log4j 属性文件?