Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 503
jjmontes Avatar asked Jan 30 '23 08:01

jjmontes


1 Answers

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!

like image 192
Vinay Sajip Avatar answered Feb 06 '23 15:02

Vinay Sajip