Python logger, print child logger %(name) without parent name

前端 未结 2 1124
我寻月下人不归
我寻月下人不归 2021-01-21 04:58

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 \'%(as

2条回答
  •  孤城傲影
    2021-01-21 05:30

    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.

提交回复
热议问题