2017-08-14 138 views
1

现在已经到了将所有打印转换为我所维护的库中的日志记录调用的时候了。一些打印话费使用str.format,像这样(简化):如何用逗号将数字记录为千位分隔符?

>>> n = 4000000 
>>> print(f"this bird wouldn't voom if you put {n:,} volts through it!") 
this bird wouldn't voom if you put 4,000,000 volts through it! 

当我尝试登录它:

>>> log.warning("this bird wouldn't voom if you put %d, volts through it!", n) 
WARNING:root:this bird wouldn't voom if you put 4000000, volts through it! 

看来这不是正确指定的千位分隔符。在使用Python的stdlib日志记录模块所需的%格式化语法时,如何指定千位分隔符?

目前使用此解决方案,为数字直接其中确实得到期望的输出,但由于变量第一次格式化使用str.format,然后重新格式化为一个字符串似乎是错误的,而不是记录:

>>> log.warning("this bird wouldn't voom if you put %s volts through it!", format(n, ',')) 
WARNING:root:this bird wouldn't voom if you put 4,000,000 volts through it! 
+2

在黑暗中拍摄:使用['logging.Formatter'](https://docs.python.org/3/library/logging.html#logging.Formatter)与'style =“{”' –

+0

So ,也许[这里](https://docs.python.org/3/howto/logging-cookbook.html#use-of-alternative-formatting-styles)会有所帮助。 –

+1

@ juanpa.arrivillaga我已经尝试过,并且无法让它工作。 '{'style用于模板格式本身,但不用于实际消息的参数。但是我可能错过了一些东西 - 如果你能得到它的工作,通过一切手段添加一个答案。 – wim

回答

2

这是与logging的限制,它在(至少在一个地方)的documentation实际上提到:

logging.debug(msg, *args, **kwargs)

在根记录器上记录等级为DEBUG的消息。 msg是消息格式字符串,参数是使用字符串格式化运算符合并到msg中的参数。 (请注意,这意味着你可以在格式字符串中使用关键字,用同一个字典参数)。

(重点煤矿)

但字符串格式化操作%不支持thousand seperators

你可以从不过官方cookbook适应配方:如果你把400万伏特通过它

import logging 

class Message(object): 
    def __init__(self, fmt, args): 
     self.fmt = fmt 
     self.args = args 

    def __str__(self): 
     return self.fmt.format(*self.args) 

class StyleAdapter(logging.LoggerAdapter): 
    def __init__(self, logger, extra=None): 
     super(StyleAdapter, self).__init__(logger, extra or {}) 

    def log(self, level, msg, *args, **kwargs): 
     if self.isEnabledFor(level): 
      msg, kwargs = self.process(msg, kwargs) 
      self.logger._log(level, Message(msg, args),(), **kwargs) 

logger = StyleAdapter(logging.getLogger(__name__)) 

def main(): 
    # this changed 
    logger.warning("this bird wouldn't voom if you put {:,} volts through it!", 4000000) 

if __name__ == '__main__': 
    logging.basicConfig(level=logging.DEBUG) 
    main() 

WARNING:__main__:这种鸟不会VOOM!

这实际上是从"Use of alternative formatting styles"部分的最后一个示例逐字复制的(我刚更改了消息)。


就我个人而言,我只想去你的format(n, ',')解决方案。它可能不完美,但它不需要设置自定义LoggerAdapter来打印不同的千分位器。

+0

呃,'StyleAdapter'真的很丑。访问受保护的'self.logger._log'并不酷。我想我会坚持解决方法。谢谢! – wim

相关问题