Last active
April 15, 2020 17:13
-
-
Save tbrlpld/551e52324380e937dde0e8a4e9cfdc7e to your computer and use it in GitHub Desktop.
Avoid function execution for not logged messages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import logging | |
| logger = logging.getLogger(__name__) | |
| # Log level is INFO. So anything of lower level (DEBUG) should not execute | |
| logger.setLevel(logging.INFO) | |
| stream_handler = logging.StreamHandler() | |
| logger.addHandler(stream_handler) | |
| urls = ("a", "c", "b", "a") | |
| def sort_urls(urls): | |
| print("Sorting urls") | |
| return sorted(urls) | |
| class LazySortedURLs(object): | |
| def __init__(self, urls): | |
| print("Instanciating") | |
| self.urls = urls | |
| def __str__(self): | |
| print("Sorting urls") | |
| return str(sorted(urls)) | |
| # The debug message is not logged, but the sorting is still executed. | |
| # This may be unimportant for small collections, but is can become very costly is the collection is large. | |
| logger.debug("Debug sorted urls: %s", sort_urls(urls)) | |
| logger.info("Info sorted urls: %s", sort_urls(urls)) | |
| # When using a custom class to wrap the sorting, it looks like the `__str__` | |
| # method is only evaluated when it is needed ("lazy"). The object is | |
| # instanciated but not printed. | |
| logger.debug("Debug lazy sorted urls: %s", LazySortedURLs(urls)) | |
| logger.info("Info lazy sorted urls: %s", LazySortedURLs(urls)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment