|
| 1 | +import logging |
| 2 | +import sys |
| 3 | + |
| 4 | +from time import time |
| 5 | + |
| 6 | + |
| 7 | +logger = logging.getLogger() |
| 8 | +logger.setLevel(logging.INFO) |
| 9 | +message_format = '%(levelname)s - %(message)s' |
| 10 | +formatter = logging.Formatter(message_format) |
| 11 | +console_handler = logging.StreamHandler(sys.stdout) |
| 12 | +console_handler.setLevel(logging.INFO) |
| 13 | +console_handler.setFormatter(formatter) |
| 14 | +logger.addHandler(console_handler) |
| 15 | + |
| 16 | + |
| 17 | +def log_function_time(): |
| 18 | + """ |
| 19 | + Returns: Prints the execution time of the decorated function to the |
| 20 | + console. If the execution time exceeds 10 minutes, it will use 'error' |
| 21 | + for the message level. Otherwise, it will use 'info'. |
| 22 | + """ |
| 23 | + def name_wrapper(function): |
| 24 | + def time_wrapper(*args, **kwargs): |
| 25 | + global logger |
| 26 | + function_name = function.__name__ |
| 27 | + |
| 28 | + start_time = time() |
| 29 | + return_value = function(*args, **kwargs) |
| 30 | + elapsed_time = time() - start_time |
| 31 | + |
| 32 | + travis_output_time_limit = 600 |
| 33 | + message_level = logging.ERROR if elapsed_time >= travis_output_time_limit \ |
| 34 | + else logging.INFO |
| 35 | + logging.disable(logging.NOTSET) |
| 36 | + logger.log(message_level, |
| 37 | + "%s completed in %s seconds...", |
| 38 | + function_name, |
| 39 | + str(elapsed_time)) |
| 40 | + logging.disable(logging.CRITICAL) |
| 41 | + |
| 42 | + return return_value |
| 43 | + return time_wrapper |
| 44 | + return name_wrapper |
0 commit comments