8

我正在使用 python 日志记录,并且我有一个如下所示的格式化程序:

formatter = logging.Formatter(
    '%(asctime)s - %(pathname)86s - %(lineno)4s - %(message)s', '%d %H:%M'
    )

如您所见,我喜欢日志文件中的信息在列中整齐排列。我为路径名保留 86 个空格的原因是因为我的程序中使用的某些文件的完整路径太长了。但是,我真正需要的是实际文件名,而不是完整路径。如何让日志记录模块只给我文件名?更好的是,因为我有一些长文件名,我想要文件名的前 3 个字符,然后是“~”,然后是最后 16 个字符。所以

/Users/Jon/important_dir/dev/my_project/latest/testing-tools/test_read_only_scenarios_happily.py

应该成为

tes~arios_happily.py
4

4 回答 4

13

您必须实现自己的 Formatter 子类,为您截断路径;格式化字符串不能这样做:

import logging
import os

class PathTruncatingFormatter(logging.Formatter):
    def format(self, record):
        if isinstance(record.args, dict) and 'pathname' in record.args:
            # truncate the pathname
            filename = os.path.basename(record.args['pathname'])
            if len(filename) > 20:
                filename = '{}~{}'.format(filename[:3], filename[-16:])
            record.args['pathname'] = filename
        return super(PathTruncatingFormatter, self).format(record)

使用此类而不是普通logging.Formatter实例:

formatter = logging.PathTruncatingFormatter(
    '%(asctime)s - %(pathname)86s - %(lineno)4s - %(message)s', '%d %H:%M'
    )
于 2013-01-20T22:00:20.410 回答
1

像这样:

import os

def shorten_filename(filename):
    f = os.path.split(filename)[1]
    return "%s~%s" % (f[:3], f[-16:]) if len(f) > 19 else f
于 2013-01-20T21:50:36.023 回答
1

您可以简单地使用文件名而不是路径名。有关详细信息,请参阅https://docs.python.org/3.1/library/logging.html#formatter-objects

于 2019-07-26T14:34:13.757 回答
0

以下是 @Martijn 编写的 Python 3 版本。正如@Nick 指出的那样,传递的记录参数是 Python 3 中的 LogRecord 对象。

import logging
import os

class PathTruncatingFormatter(logging.Formatter):
    def format(self, record):
        if 'pathname' in record.__dict__.keys():
            # truncate the pathname
            filename = os.path.basename(record.pathname)
            if len(filename) > 20:
                filename = '{}~{}'.format(filename[:3], filename[-16:])
            record.pathname = filename
        return super(PathTruncatingFormatter, self).format(record)
于 2019-07-12T09:34:47.047 回答