我正在使用 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
最佳答案
您必须实现自己的 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'
)
关于python 日志记录 - 如何将路径名截断为最后几个字符或文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14429724/