python - Why is my logging filter being applied to the wrong handler? -


here's simple python filter nothing put "test - " in front of log message. (the real filter more helpful processing later):

class timestamp_filter(logging.filter):     def filter(self, record):         record.msg = "test - " + str(record.msg)         return true 

and here's config being pulled in json file , parsed dictconfig():

{     "version": 1,     "disable_existing_loggers": false,     "filters": {         "timestamp_filter": {             "()": "timestamp_filter"         }     },     "handlers": {         "file_handler": {             "class": "logging.filehandler",             "level": "info",             "filename": "../log/default.log",             "mode": "a"                               },         "console": {             "class": "logging.streamhandler",             "level": "debug",             "filters": ["timestamp_filter"],             "stream": "ext://sys.stdout"         }     },     "root": {         "level": "debug",         "handlers": ["console", "file_handler"]     } } 

the filter seems work - if create logger , run logger.info("hello, world!"), output test - hello, world! on screen.

however also output (including "test") in default.log file. had thought attaching timestamp_filter console handler, test output on screen.

why being sent file_handler handler , ending in log file?

you changing message of log record filter. causing issue.

python apply filter console output alright when does, changes original log message. when log message passed file handler, message has changed , contains input.

if want change log format specific handlers, should consider using formatters instead. filtering selecting message gets logged , 1 should not.

update: per comments, here's sample code explaining how can use custom formatter , handle business logic inside it.

import logging import sys   class customformatter(logging.formatter):     def format(self, record):         mycondition = true  # here goes business logic         formatted_message = super().format(record=record)          if mycondition:             formatted_message += "test"          return formatted_message   logger = logging.getlogger("test") logger.setlevel(logging.debug)  handler = logging.streamhandler(stream=sys.stdout) handler.setformatter(customformatter()) logger.addhandler(handler)    logger.info("hello!") 

Comments