quarkslab / irma-brain

IRMA brain
21 stars 4 forks source link

Use lazy string formatting in logging calls #10

Closed zopieux closed 9 years ago

zopieux commented 9 years ago

I've seen many instances of code (if not all) that uses raw string formatting such as:

# https://github.com/quarkslab/irma-brain/blob/1e5e52ca2b1cab3ea279776085f102f90c91e244/brain/tasks.py#L68
log.info("{0}: Found user".format(frontend_scanid) + 
         "quota remaining {0}/{1}".format(remaining, quota)) 

The right way™ is to pass parameters to the log.{debug,info,warning,error} methods and use printf placeholders, so that string formatting, which is quite an expensive computation, is only done when it's needed. Eg. if I disable logging or set it to warning level, there is no need to compute debug and info strings.

log.info("%s: Found user quota remaining %d/%d", frontend_scanid, remaining, quota)

Note this is not only a performance improvement, it also prevents the program from crashing because of an exception during the string formatting in a message that was not supposed to be shown:

logging.basicConfig(level=logging.WARNING)
n = "not a number"
logging.debug("this is not shown, does not crash %d", n)
logging.debug("this is not shown, but crashes %d" % n)
ch0k0bn commented 9 years ago

closed by commit c3650e11cf9fb4430a1654f15fd2d6a75e9286bd