简体   繁体   中英

abbreviate or shorten the logger name to initials with python logging

I'm trying to achieve a behavior available in log4j, which is described in this SO Q&A

Instead of the logger producing the following output (notice the full module name)

DEBUG    aproject.bpackage.cclass:filename.py:79 log message 1

I'd like to only have the initials of the logger name :

DEBUG    a.b.c:filename.py:79 log message 1

Trying to figure out the correct format string with the manual , but no mention of initials for the logger name

Note that loggers are initialized with the module name as convention:
logger = logging.getLogger(__name__)

There's no out-of-the-box functionality for this, but you can achieve the desired result using something like this:

import logging

class CustomFormatter(logging.Formatter):
    def format(self, record):
        saved_name = record.name  # save and restore for other formatters if desired
        parts = saved_name.split('.')
        # import pdb; pdb.set_trace()
        record.name = '.'.join(p[0] for p in parts)
        result = super().format(record)
        record.name = saved_name
        return result

h = logging.StreamHandler()
f = CustomFormatter('%(name)-6s %(message)s')
h.setFormatter(f)
root = logging.getLogger()
root.addHandler(h)
root.setLevel(logging.DEBUG)
logging.getLogger('alpha.beta.gamma').debug('foo')
logging.getLogger('delta.epsilon.zeta').debug('bar')
logging.getLogger('eta.theta').debug('baz')

When run, the above script outputs

a.b.g  foo
d.e.z  bar
e.t    baz

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