python logging - how do I truncate the pathname to just the last few characters or just the filename?
You'll have to implement your own Formatter subclass that truncates the path for you; the formatting string cannot do this:
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)
Use this class instead of the normal logging.Formatter
instance:
formatter = logging.PathTruncatingFormatter(
'%(asctime)s - %(pathname)86s - %(lineno)4s - %(message)s', '%d %H:%M'
)