我正在使用python的日志formatter格式化log records我的 fmt 值为
fmt = "[%(filename)s:%(lineno)s] %(message)s"
我想要将“[file.py:20]”拉伸(stretch)到 10 个字符宽(例如)。如果这是一个很容易的值,但有没有办法将整个结构拉伸(stretch)到指定的长度? 我想要类似的东西:
tmp = "[%(filename)s:%(lineno)s]"
fmt = "%(tmp)10s %(message)s"
我想知道这是否可以使用字符串格式化,或者我是否可以以某种方式欺骗 python 的格式化程序以获得我想要的..
最佳答案
例如,此格式化程序通过截断文件名或右填充(在行号之后)来确保固定宽度 "[%(filename)s:%(lineno)s]"
) 带空格。
class MyFormatter(logging.Formatter):
width = 10
def format(self, record):
max_filename_width = self.width - 3 - len(str(record.lineno))
filename = record.filename
if len(record.filename) > max_filename_width:
filename = record.filename[:max_filename_width]
a = "%s:%s" % (filename, record.lineno)
return "[%s] %s" % (a.ljust(self.width), record.msg)
if __name__ == '__main__':
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = MyFormatter()
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.debug('No one expects the spammish repetition')
编辑:
如果您想确保最小宽度为 10 个字符,请放弃文件名内容。
def format(self, record):
a = "%s:%s" % (record.filename, record.lineno)
return "[%s] %s" % (a.ljust(self.width), record.msg)
关于python记录字符串格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6692248/