Skip to content

Instantly share code, notes, and snippets.

@mmngreco
Created July 27, 2022 07:21
Show Gist options
  • Save mmngreco/a128cc0b6cf6f1d5d844619ede62541d to your computer and use it in GitHub Desktop.
Save mmngreco/a128cc0b6cf6f1d5d844619ede62541d to your computer and use it in GitHub Desktop.
# log_issue.py
"""
We want logging the output of a heavy_task function when the log level is debug.
The problem appears when we use info level and the whole process is being
affected by our debug log statement.
main : reproduce the problem
main_lazy : has the solution.
"""
import logging
from time import sleep
def heavy_task():
"""Consume time and returna a value.
The generic goal of this function is to process a lot of info and return
human readable output.
"""
sleep(3)
return 3
def main():
"""Reproduce the problem"""
for i in range(3):
logging.info("%s", i)
logging.debug("%s", heavy_task())
# ----------------------------------------------------------------------------
# alternative
class LazyfyStr(object):
# Taken from https://stackoverflow.com/a/52359695
__slots__ = 'fn', 'args'
def __init__(self, fn, *args):
self.fn = fn
self.args = args
def __str__(self):
return str(self.fn(*self.args))
def main_lazy():
"""Solution"""
for i in range(3):
logging.info("%s", i)
logging.debug("%s", LazyfyStr(heavy_task))
# ----------------------------------------------------------------------------
# execution
if __name__ == "__main__":
import sys
logging.basicConfig(level=logging.INFO)
try:
lazy = sys.argv[1].lower() == "lazy"
except IndexError:
lazy = False
if lazy:
logging.info("Running lazy mode")
main_lazy()
else:
logging.info("Running standar mode")
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment