Python logger, print child logger %(name) without parent name
Asked Answered
Y

2

4

I am trying Python logging.

Since I want some logger to share a formatter, I use hierarchy of logging like the below code.

As you can see, format is '%(asctime)s - %(name)s - %(message)s'

At this point, I want loggers to print the %(name)s part without the parent name.

I mean, normally it will print the name as 'SYS.Start Up Routine' but I want 'Start Up Routine'

Is there any way?

logging.root.level = logging.DEBUG
logger = logging.getLogger('SYS')
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(message)s')

streamHandler = logging.StreamHandler()
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)

logger1 = logging.getLogger("SYS.Start Up Routine")
logger2 = logging.getLogger("SYS.Message Layer")
logger3 = logging.getLogger("SYS.Application Layer")
Yearly answered 4/9, 2014 at 17:16 Comment(0)
P
1

If you want the name to say 'bar' instead of 'foo.bar', just log to a logger named 'bar', and add your handlers to the root logger.

Puzzler answered 4/9, 2014 at 18:35 Comment(1)
This solution has a notable caveat: changing the logger name like this does not allow to group loggers and configure them in groups (using the parent logger name).Pothook
F
2

Add a context filter to your example:

class ContextFilter:
    def filter(self, record):
        split_name = record.name.split('.', 1)
        if split_name[0] = 'SYS':
            record.name = split_name[1]

And then add it to the handler:

streamHandler.addFilter(ContextFilter())

The handler filter is the last part of the logging flow. This filter changes the name at that point. This allows you to use SYS as the root of all your loggers (which is good practice) and it allows the end user to decide on formatting. You're the consumer of your own logs here and you only want to print to stdout, but that won't always be the case.

You could add a file handler, set it to debug, and NOT add the context filter so it DOES include SYS because now it's including a whole bunch of other loggers and the root is important.

Frogfish answered 6/6, 2018 at 5:16 Comment(0)
P
1

If you want the name to say 'bar' instead of 'foo.bar', just log to a logger named 'bar', and add your handlers to the root logger.

Puzzler answered 4/9, 2014 at 18:35 Comment(1)
This solution has a notable caveat: changing the logger name like this does not allow to group loggers and configure them in groups (using the parent logger name).Pothook

© 2022 - 2024 — McMap. All rights reserved.