Function call monitor. Parameters: name_style (str): style of displayed function name, can be `full`, `class` or `func`
| 124 | |
| 125 | |
| 126 | class Monitor(object): |
| 127 | """ |
| 128 | Function call monitor. |
| 129 | |
| 130 | Parameters: |
| 131 | name_style (str): style of displayed function name, |
| 132 | can be `full`, `class` or `func` |
| 133 | """ |
| 134 | |
| 135 | def __init__(self, name_style="class"): |
| 136 | assert name_style in ["full", "class", "func"] |
| 137 | self.name_style = name_style |
| 138 | |
| 139 | def get_name(self, function, instance): |
| 140 | is_method = function.__code__.co_argcount > 0 and function.__code__.co_varnames[0] == "self" |
| 141 | if self.name_style == "func" or not is_method: |
| 142 | return "%s" % function.__name__ |
| 143 | if self.name_style == "class": |
| 144 | return "%s.%s" % (instance.__class__.__name__, function.__name__) |
| 145 | if self.name_style == "full": |
| 146 | return "%s.%s.%s" % (instance.__module__, instance.__class__.__name__, function.__name__) |
| 147 | |
| 148 | def time(self, function): |
| 149 | """ |
| 150 | Monitor the run time of a function. |
| 151 | |
| 152 | Parameters: |
| 153 | function (function): function to monitor |
| 154 | |
| 155 | Returns: |
| 156 | function: wrapped function |
| 157 | """ |
| 158 | @wraps(function) |
| 159 | def wrapper(*args, **kwargs): |
| 160 | name = self.get_name(function, args[0]) |
| 161 | start = time() |
| 162 | result = function(*args, **kwargs) |
| 163 | end = time() |
| 164 | logger.info("[time] %s: %g s" % (name, end - start)) |
| 165 | return result |
| 166 | |
| 167 | return wrapper |
| 168 | |
| 169 | def call(self, function): |
| 170 | """ |
| 171 | Monitor the arguments of a function. |
| 172 | |
| 173 | Parameters: |
| 174 | function (function): function to monitor |
| 175 | |
| 176 | Returns: |
| 177 | function: wrapped function |
| 178 | """ |
| 179 | @wraps(function) |
| 180 | def wrapper(*args, **kwargs): |
| 181 | name = self.get_name(function, args[0]) |
| 182 | strings = ["%s" % repr(arg) for arg in args] |
| 183 | strings += ["%s=%s" % (k, repr(v)) for k, v in kwargs.items()] |