2017-08-14 135 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

相關問題