Idiomatic Python logging: format string + args list vs. inline string formatting - which is preferred?

后端 未结 3 1635
予麋鹿
予麋鹿 2021-01-04 02:10

Is it advantageous to call logging functions with format string + args list vs. formatting inline?

I\'ve seen (and written) logging code that uses inline string form

3条回答
  •  天涯浪人
    2021-01-04 03:12

    Avoiding inline string formatting does save some time if the current logging level filters the log message (as I expected) -- but not much:

    In [1]: import logging
    
    In [2]: logger = logging.getLogger('foo')
    
    In [3]: logger.setLevel(logging.ERROR)
    
    In [4]: %timeit -n 1000000 logger.warn('%s %s %s' % ('a', 'b', 'c'))
    1000000 loops, best of 3: 1.09 us per loop
    
    In [12]: %timeit -n 1000000 logger.warn('%s %s %s', 'a', 'b', 'c')
    1000000 loops, best of 3: 946 ns per loop
    

    So, as user1202136 pointed out, the overall performance difference depends on how long it takes to format the string (which could be significant depending on the cost of calling __str__ on arguments being passed to the logging function.)

提交回复
热议问题