Add information to every log message in Python logging

前端 未结 3 2011
深忆病人
深忆病人 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 10:02

    You can configure the logging module by adding a custom format option like so

    import logging
    
    name = socket.hostname() 
    logMessageFormat = '{}: %(levelname)s:%(message)s'.format(name)
    logging.basicConfig(format=logMessageFormat, level=logging.DEBUG)
    
    # Test new configuration
    logger = logging.getLogger()
    logger.info('Hello world')
    
    # should print to the console
    # : INFO:Hello world
    

    You can read more about customizing the format of displayed messages here https://docs.python.org/3/howto/logging.html#changing-the-format-of-displayed-messages

提交回复
热议问题