Apply python logging format to each line of a message containing new lines -
i include id associated request every log line in log file. have mechanism retrieving request id via logging filter working fine.
my problem when log line contains newline, line of course wrapped onto "bare" line. there way tell logging library split message, , apply format each element of split?
import logging logger = logging.getlogger() handler = logging.streamhandler() formatter = logging.formatter( "%(requestid)s\t%(message)s") handler.setformatter(formatter) logger.addhandler(handler) logger.setlevel(logging.debug) logger.debug("blah\nblah")
output:
xxx blah blah
desired output:
xxx blah xxx blah
though not best way go this, without changing lot of code.
import logging class customhandler(logging.streamhandler): def __init__(self): super(customhandler, self).__init__() def emit(self, record): messages = record.msg.split('\n') message in messages: record.msg = message super(customhandler, self).emit(record) log = logging.getlogger() handler = customhandler() formattor = logging.formatter("xxx:%(message)s") handler.setformatter(formattor) log.addhandler(handler) log.setlevel(logging.debug) if __name__ == '__main__': log.debug('hello\nhi')
output:
xxx:hello xxx:hi
Comments
Post a Comment