jjmontes
jjmontes

Reputation: 26904

Python logging format: how to print only the last part of logger name?

I'm using python logging with the following format string:

'format': '%(asctime)s %(levelname)s %(name)s - %(message)s'

The %(name)s part prints the logger name:

2017-10-26 13:17:58,019 INFO device_gps.comm.protocol - GPSProtocol(port=COM13) - Starting GPS serial communications (port: COM13)
2017-10-26 13:17:58,022 INFO scs_control.context - Starting component: DeviceGPS
2017-10-26 13:17:58,033 INFO scs_elevation.elevation - Initializing ElevationModel engine instance.

Like with other logging facilities (like log4j) I'd like to print only the last part of the logger name for brevity (shown in bold in the example above).

This other answer suggests to change the logger name, but doing so would destroy the parent-child logger relationship, which is really useful to configure logging for a group of loggers.

How can I have python logging print the last part of a logger name?

Upvotes: 9

Views: 13135

Answers (2)

Vinay Sajip
Vinay Sajip

Reputation: 99385

You can set a filter to set a LogRecord attribute to the last part of the logger name, and use that in your format string. For example, running this script:

import logging

class LastPartFilter(logging.Filter):
    def filter(self, record):
        record.name_last = record.name.rsplit('.', 1)[-1]
        return True

logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter('%(name_last)s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
handler.addFilter(LastPartFilter())

logging.getLogger('foo').warning('Watch out - foo!')
logging.getLogger('foo.bar').warning('Watch out - foo.bar!')
logging.getLogger('foo.bar.baz').warning('Watch out - foo.bar.baz!')

produces this:

foo Watch out - foo!
bar Watch out - foo.bar!
baz Watch out - foo.bar.baz!

Upvotes: 11

Kendas
Kendas

Reputation: 2243

The attributes available for use in logging are listed here

You probably want your format to be '%(asctime)s %(levelname)s %(module)s - %(message)s'.

Upvotes: 2

Related Questions