有時我使用%(funcName)s
配置python日誌記錄格式化程序。但是當函數名稱很長時,我不喜歡這個。使用python logging`%(funcName)s`時,可以縮短日誌標題嗎?
使用python logging可以縮短日誌標題嗎%(funcName)s
?如果是,如何?
你能說...將字符總數限制爲10個字符嗎?
有時我使用%(funcName)s
配置python日誌記錄格式化程序。但是當函數名稱很長時,我不喜歡這個。使用python logging`%(funcName)s`時,可以縮短日誌標題嗎?
使用python logging可以縮短日誌標題嗎%(funcName)s
?如果是,如何?
你能說...將字符總數限制爲10個字符嗎?
在日誌記錄格式字符串%(...)s
項目是更換%,你可以通過執行類似%(funcName).10s
如限制一個字符串替換的長度
import logging
logging.basicConfig(
format='%(funcName).10s %(message)s',
level=logging.INFO,
)
logger = logging.getLogger()
def short():
logger.info("I'm only little!")
def really_really_really_really_long():
logger.info("I'm really long")
short()
really_really_really_really_long()
給
[email protected][17:54:01]:~$ p tmp_x.py
short I'm only little!
really_rea I'm really long
道具爲優雅的解決方案(我沒有想過要使用字符串格式的「。」...我只使用了字符串格式功能,當做浮點'%f'字符串格式)。另外一點:如果將'%.10s'更改爲'10.10s',那麼當函數太短(使您的日誌記錄標題長度不變)時,將獲得恆定大小10。 –
@TrevorBoydSmith這很方便知道。你有沒有能夠找到一些體面的文件來說明你可以用'%s'做什麼?我真的想鏈接到一些文檔,但我發現的頁面只提到'%s'在對象上調用'str()',但對修飾符沒有太多要求。 –
我相信[您正在尋找的官方python文檔在這裏](https://docs.python.org/2/library/string.html#formatspec)。 (如果你知道c樣式的printf,那麼通常情況下相同,但C是不同的語言,因此語法可能不完全相同(比較語法是另一次的討論)。) –
您可以擴展logging.formatter
類以獲得所需的格式,如下所示。
這只是一個例子。 in_console =假 高清初始化(個體經營): self.mod_width = 30 self.datefmt =「%H:%M:%S,你應該根據你的要求 類MyFormatter(logging.Formatter)修改「
def format(self, record):
s = []
cmodule = record.module + ":" + str(record.lineno)
cmodule = cmodule[-self.mod_width:].ljust(self.mod_width)
format_str = ("%-7s %s %s" % (record.levelname, self.formatTime(record, self.datefmt), cmodule))
pad_len = len(format_str)
for line in record_msg[1:]:
line = " " * pad_len + " : " + line
s.append(line)
s = "%s : %s" % (format_str, "\n".join(s))
return s
my_formatter = MyFormatter()
log.setFormatter(my_formatter)
您可以發佈您希望改善一些代碼? –