Add information to every log message in Python logging

前端 未结 3 2006
深忆病人
深忆病人 2021-01-15 09:23

I am using Python with logging module and would like to add the socket.hostname() to every log message, I have to run this query every message and can not use



        
3条回答
  •  攒了一身酷
    2021-01-15 09:57

    You can use filter to add information to every message :

    import logging
    import socket
    
    class ContextFilter(logging.Filter):
        def filter(self, record):
            record.hostname = socket.gethostname() 
            return True
    
    if __name__ == '__main__':
        levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
        logging.basicConfig(level=logging.DEBUG,
                            format='%(asctime)-15s hostname: %(hostname)-15s : %(message)s')
        a1 = logging.getLogger('a.b.c')
        f = ContextFilter()
        a1.addFilter(f)
        a1.debug('A debug message')
    

提交回复
热议问题