For debugging purpose I want to write a function to do this:
- If debug_mode == 0 doesn't echo any message.
- If debug_mode == 1 echoes the message to the stdout with print()
- If debug_mode == 2 echoes the message to a log file
I've thinked do that with function decorators (that I've never used before).
Actually, I want to substitute some print()
that I've put in some points to show me intermediate values and while learn about function decorators.
I don't want to create a class to do that. This is my approach, but it doesn't work:
import logging
FORMAT = '%(asctime)s %(levelname)s %(message)s %(funcName)s'
logging.basicConfig(filename='example.log', level=logging.DEBUG, format=FORMAT, datefmt='%m/%d/%Y %I:%M:%S %p')
def debug(func):
def _debug(deb=0, *args, **kwargs):
if deb == 1:
print(msg)
func(*args, **kwargs)
if deb == 2:
logging.debug(msg)
return _debug
@debug
def echo(msg, deb=0):
pass
if __name__ == "__main__":
debug_mode = 1
echo("This is a debugging message!", debug_mode)
It will be better if I haven't to pass the param debug_mode and in the decorator function I can use the debug state directly from the __main__
.