|
| 1 | +# Copyright 2023 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import functools |
| 16 | +import threading |
| 17 | +from typing import List |
| 18 | + |
| 19 | +_lock = threading.Lock() |
| 20 | +MAX_LABELS_COUNT = 64 |
| 21 | +_api_methods: List = [] |
| 22 | + |
| 23 | + |
| 24 | +def class_logger(decorated_cls): |
| 25 | + """Decorator that adds logging functionality to each method of the class.""" |
| 26 | + for attr_name, attr_value in decorated_cls.__dict__.items(): |
| 27 | + if callable(attr_value): |
| 28 | + setattr(decorated_cls, attr_name, method_logger(attr_value)) |
| 29 | + return decorated_cls |
| 30 | + |
| 31 | + |
| 32 | +def method_logger(method): |
| 33 | + """Decorator that adds logging functionality to a method.""" |
| 34 | + |
| 35 | + @functools.wraps(method) |
| 36 | + def wrapper(*args, **kwargs): |
| 37 | + api_method_name = str(method.__name__) |
| 38 | + # Track regular and "dunder" methods |
| 39 | + if api_method_name.startswith("__") or not api_method_name.startswith("_"): |
| 40 | + add_api_method(api_method_name) |
| 41 | + return method(*args, **kwargs) |
| 42 | + |
| 43 | + return wrapper |
| 44 | + |
| 45 | + |
| 46 | +def add_api_method(api_method_name): |
| 47 | + global _lock |
| 48 | + global _api_methods |
| 49 | + with _lock: |
| 50 | + # Push the method to the front of the _api_methods list |
| 51 | + _api_methods.insert(0, api_method_name) |
| 52 | + # Keep the list length within the maximum limit (adjust MAX_LABELS_COUNT as needed) |
| 53 | + _api_methods = _api_methods[:MAX_LABELS_COUNT] |
| 54 | + |
| 55 | + |
| 56 | +def get_and_reset_api_methods(): |
| 57 | + global _lock |
| 58 | + with _lock: |
| 59 | + previous_api_methods = list(_api_methods) |
| 60 | + _api_methods.clear() |
| 61 | + return previous_api_methods |
0 commit comments