簡體   English   中英

如何在 Python 的日志記錄模塊中使用現代字符串格式選項?

[英]How to use modern string formatting options with Python's logging module?

Python 日志教程說更新的格式化方法超出了教程的范圍,但沒有提及從哪里了解它。

我將不勝感激任何允許我在日志記錄調用中使用.format()樣式消息格式的示例或文檔鏈接,例如debug()info()等。

最近,我也在找那個。 我想我在 SO 上指出了解決方案,但我手頭只有最終 url。 這就是我所做的:

# http://plumberjack.blogspot.de/2010/10/supporting-alternative-formatting.html
class BraceMessage(object):
    def __init__(self, fmt, *args, **kwargs):
        self.fmt = fmt
        self.args = args
        self.kwargs = kwargs

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

_F = BraceMessage

可以這樣使用:

logger.debug(_F("foo {0} {quux}", bar, quux=baz))

格式化只會在評估消息的那一刻發生,因此如果禁用日志級別,您不會損失很多性能。 上面那個片段的作者將它(和一些其他實用程序)作為一個包提供: logutils

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM