简体   繁体   中英

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. - GPSProtocol(port=COM13) - Starting GPS serial communications (port: COM13)
2017-10-26 13:17:58,022 INFO scs_control. - Starting component: DeviceGPS
2017-10-26 13:17:58,033 INFO scs_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?

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!

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' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM