【问题标题】:python logging - how do I truncate the pathname to just the last few characters or just the filename?python logging - 如何将路径名截断为最后几个字符或文件名?
【发布时间】:2013-01-03 23:33:20
【问题描述】:

我正在使用 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

【问题讨论】:

  • 我看到了你的编辑建议;很高兴你解决了。 record.args 是字典或元组,但您的格式化程序建议您专门使用字典,这就是我基于此创建解决方案的原因。正如您所发现的,适应元组也很容易。 :-)

标签: python logging


【解决方案1】:

您必须实现自己的 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'
    )

【讨论】:

  • python3.4,路径名在record.pathname
  • 如果我使用 logging.ini 文件,有没有办法做到这一点?
  • @SouravPrem:不,因为您不能在logging.ini 中定义自定义类。
【解决方案2】:

像这样:

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

【讨论】:

  • 次要,我会使用len(f) > 20,因为无论如何缩短的文件名将有 20 个字符(19 个来自文件名加上波浪号)。
  • 谢谢。但是,这个答案并没有解决日志模块上下文中的问题。
【解决方案3】:

您可以简单地使用文件名而不是路径名。更多详情请参考https://docs.python.org/3.1/library/logging.html#formatter-objects

【讨论】:

    【解决方案4】:

    以下是 @Martijn 编写的 Python 3 版本。正如@Nick 指出的那样,传递的 record 参数是 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)
    

    【讨论】:

      猜你喜欢
      • 2021-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-01
      • 2016-10-14
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      相关资源
      最近更新 更多