python日志字符串格式

ale*_*poi 10 python formatting logging string-formatting

我使用python的日志格式化器来格式化日志记录,我的fmt值为

fmt = "[%(filename)s:%(lineno)s] %(message)s"
Run Code Online (Sandbox Code Playgroud)

我想要的是"[file.py:20]"被拉伸到10个字符宽(例如).如果它是一个很容易的值,但有没有办法将整个结构拉伸到指定的长度?我想要的东西:

tmp = "[%(filename)s:%(lineno)s]"
fmt = "%(tmp)10s %(message)s"
Run Code Online (Sandbox Code Playgroud)

我想知道是否可以使用字符串格式化,或者如果我可以欺骗python的格式化程序以某种方式得到我想要的东西..

Rob*_*wie 12

例如,此Formatter "[%(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')
Run Code Online (Sandbox Code Playgroud)

编辑:

如果要确保最小宽度为10个字符,请丢弃文件名.

def format(self, record):
    a = "%s:%s" % (record.filename, record.lineno)
    return "[%s] %s" % (a.ljust(self.width), record.msg)
Run Code Online (Sandbox Code Playgroud)


S.L*_*ott 9

选项1

从这里开始:http://docs.python.org/library/logging.html#formatter-objects

您将创建自己的自定义子类,Formatter它提供了自己独特的format方法.

然后你必须确保打电话给setFormatter()你的每一个,Handlers以便他们使用你的新格式化器.

选项2

使用其他属性创建自己的LogRecord子类.

子类Logger和重写makeRecord来创建新的子类LogRecord.

提供使用此新属性值的自定义格式.