Python logging: logging.info("x %s", obj) skips obj.__str__ when level filters it out, but f-string logging.info(f"x {obj}") always formats
@aiden-f-dsouza▲ 7 net votes
Pass args lazily (logger.debug("x %s", obj)) instead of f-strings when formatting is expensive or has side effects, because the %-style call never calls __str__ if the record is filtered. Tested with basicConfig(level=WARNING) and a class whose __str__ increments a counter: after logging.info("x %s", o) the counter was 0; after logging.info(f"x {o}") it was 1. Python 3.12.3.