How to set width of combined fields in Python logging
<p>In Python logging, is there a way to set the width of two combined fields?</p>

<p>I'm looking to combine filenames and line numbers to produce output similar to:</p>

<pre><code>2011-10-14 13:47:51 main.py:12       DEBUG - Initializing cluster
2011-10-14 13:47:51 cluster.py:364   DEBUG - Starting cluster
2011-10-14 13:47:51 cluster.py:98    INFO  - Starting simulation
2011-10-14 13:47:51 simulation.py:79 DEBUG - Computing parameters
</code></pre>

<p>How would I modify the formatting string below, to achieve this?</p>

<pre><code>logging.Formatter('%(asctime)s %(filename)s:%(lineno)s %(levelname)5s - %(msg)s 
</code></pre>

<hr>

<p><strong>UPDATE:</strong></p>

<p>As @jonrsharpe points out, no out-of-the-box way to do this, so have customize the formatting.</p>

<p>Solution: @alecxe recommends a custom <code>Filter</code>, and here is a complete example:</p>

<pre><code>import logging
import logging.config

class FilenameLinenoFilter(logging.Filter):
    def filter(self, record):
        record.filename_lineno = '{}:{}'.format(record.filename, record.lineno)
        return True

LOG_SETTINGS = {
    'version': 1,
    'filters': {
        'filename_lineno_filter': {
            '()': FilenameLinenoFilter,
        },
    },
    'formatters': {
        'standard': {
            'format': '%(asctime)s %(filename_lineno)-18s %(levelname)5s - %(msg)s',
        },
    },
    'handlers': {
        'default': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'filters': ['filename_lineno_filter'],
            'formatter': 'standard',
            },
    },
    'loggers': {
        '': { 
            'handlers': ['default'],
            'level': 'DEBUG',
        },
    }
}

logging.config.dictConfig(LOG_SETTINGS)
logger = logging.getLogger()
logger.debug('Debug output goes here.')
logger.info('Informational goes here.')
</code></pre>