Lazy logger message string evaluation

前端 未结 6 728
囚心锁ツ
囚心锁ツ 2020-12-02 11:12

I\'m using standard python logging module in my python application:

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(\"log\")
whi         


        
6条回答
  •  囚心锁ツ
    2020-12-02 11:35

    import logging
    import time
    
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger("log")
    
    class Lazy(object):
        def __init__(self,func):
            self.func=func
        def __str__(self):
            return self.func()
    
    logger.debug(Lazy(lambda: time.sleep(20)))
    
    logger.info(Lazy(lambda: "Stupid log message " + ' '.join([str(i) for i in range(20)])))
    # INFO:log:Stupid log message 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
    

    If you run the script, you'll notice the first logger.debug command does not take 20 seconds to execute. This shows the argument is not evaluated when the logging level is below the set level.

提交回复
热议问题