python日志 - 如何将路径名截断为最后几个字符或只是文件名?

jon*_*omo 7 python logging

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

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

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

/Users/Jon/important_dir/dev/my_project/latest/testing-tools/test_read_only_scenarios_happily.py
Run Code Online (Sandbox Code Playgroud)

应该成为

tes~arios_happily.py
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 10

您必须实现自己的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)
Run Code Online (Sandbox Code Playgroud)

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

formatter = logging.PathTruncatingFormatter(
    '%(asctime)s - %(pathname)86s - %(lineno)4s - %(message)s', '%d %H:%M'
    )
Run Code Online (Sandbox Code Playgroud)

  • 使用`python3.4`,路径名在`record.pathname`中。 (2认同)