Last active
November 11, 2016 12:11
-
-
Save guyarad/15ab88ebbf5fdefab9dbceec888a3a37 to your computer and use it in GitHub Desktop.
Lazy Logging - the below snippet is relevant when you wish to log some debugging information, but that information is relatively costly to generate. Ideally, you'll want to generate that information only when DEBUG level is actually enabled. In other words, only when the message formatting actually occurs.
This file contains 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
# IMPLEMENTATION | |
class LazyLogging(object): | |
""" | |
A utility class that wraps a method | |
""" | |
def __init__(self, function): | |
self.function = function | |
def __str__(self): | |
return str(self.function()) | |
# USAGE | |
class MyClass(object): | |
def __init__(self): | |
self._lazy_debugging_info = LazyLogging(self._debugging_info) | |
# implementation detail: it's important to not that even though | |
# `_debugging_info` is a descriptor (as all the methods), passing | |
# the value returned from `self._debugging_info` produces a | |
# bound function object (so no need to pass `self` or anything | |
# of the sort) | |
def _debugging_info(self): | |
# generate some string | |
# from quite a few fields in this | |
# class and return | |
return "my debugging string" | |
def some_other_method(self): | |
# do some stuff... | |
# and debug log | |
logger.debug("I didn't some stuff. Info: %s", self._lazy_debugging_info) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This seems very inefficient and cumbersome to me. You need to create
LazyLogging
objects for each object and for each debug generating method (_debugging_info
above). Furthermore you must write those debug generating methods to use this approach:These debug generating methods (
_debug_*
) may fit your needs and your coding style. However, personally, I think it is rather inconvenient. Nevertheless, even in this scenario, I see no need to create those expensiveLazyLogging
instances:If you want to improve this, you may extend the logger class with a
lazy_debug
method, which is hard though, IIRC.