Spaces:
Paused
Paused
Create utils/debug_utils.py
Browse files- api/utils/debug_utils.py +70 -0
api/utils/debug_utils.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# FILE: api/utils/debug_utils.py
|
| 2 |
+
# DESCRIPTION: A utility for detailed function logging and debugging.
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import functools
|
| 6 |
+
import logging
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
# Define o nível de log. Mude para "INFO" para desativar os logs detalhados.
|
| 10 |
+
# Você pode controlar isso com uma variável de ambiente.
|
| 11 |
+
LOG_LEVEL = os.environ.get("ADUC_LOG_LEVEL", "DEBUG").upper()
|
| 12 |
+
logging.basicConfig(level=LOG_LEVEL, format='[%(levelname)s] [%(name)s] %(message)s')
|
| 13 |
+
logger = logging.getLogger("AducDebug")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _format_value(value):
|
| 17 |
+
"""Formata os valores dos argumentos para uma exibição concisa e informativa."""
|
| 18 |
+
if isinstance(value, torch.Tensor):
|
| 19 |
+
return f"Tensor(shape={list(value.shape)}, device='{value.device}', dtype={value.dtype})"
|
| 20 |
+
if isinstance(value, str) and len(value) > 70:
|
| 21 |
+
return f"'{value[:70]}...'"
|
| 22 |
+
if isinstance(value, list) and len(value) > 5:
|
| 23 |
+
return f"List(len={len(value)})"
|
| 24 |
+
if isinstance(value, dict) and len(value.keys()) > 5:
|
| 25 |
+
return f"Dict(keys={list(value.keys())[:5]}...)"
|
| 26 |
+
return repr(value)
|
| 27 |
+
|
| 28 |
+
def log_function_io(func):
|
| 29 |
+
"""
|
| 30 |
+
Um decorador que registra as entradas, saídas e exceções de uma função.
|
| 31 |
+
Ele é ativado apenas se o nível de log estiver definido como DEBUG.
|
| 32 |
+
"""
|
| 33 |
+
@functools.wraps(func)
|
| 34 |
+
def wrapper(*args, **kwargs):
|
| 35 |
+
# Só executa a lógica de log se o nível for DEBUG
|
| 36 |
+
if logger.isEnabledFor(logging.DEBUG):
|
| 37 |
+
# Obtém o nome do módulo e da função
|
| 38 |
+
func_name = f"{func.__module__}.{func.__name__}"
|
| 39 |
+
|
| 40 |
+
# Formata os argumentos de entrada
|
| 41 |
+
args_repr = [_format_value(a) for a in args]
|
| 42 |
+
kwargs_repr = {k: _format_value(v) for k, v in kwargs.items()}
|
| 43 |
+
signature = ", ".join(args_repr + [f"{k}={v}" for k, v in kwargs_repr.items()])
|
| 44 |
+
|
| 45 |
+
# Log de Entrada
|
| 46 |
+
logger.debug(f"================ INÍCIO: {func_name} ================")
|
| 47 |
+
logger.debug(f" -> ENTRADA: ({signature})")
|
| 48 |
+
|
| 49 |
+
try:
|
| 50 |
+
# Executa a função original
|
| 51 |
+
result = func(*args, **kwargs)
|
| 52 |
+
|
| 53 |
+
# Formata e registra o resultado
|
| 54 |
+
result_repr = _format_value(result)
|
| 55 |
+
logger.debug(f" <- SAÍDA: {result_repr}")
|
| 56 |
+
|
| 57 |
+
except Exception as e:
|
| 58 |
+
# Registra qualquer exceção que ocorra
|
| 59 |
+
logger.error(f" <-- ERRO em {func_name}: {e}", exc_info=True)
|
| 60 |
+
raise # Re-lança a exceção para não alterar o comportamento do programa
|
| 61 |
+
finally:
|
| 62 |
+
# Log de Fim
|
| 63 |
+
logger.debug(f"================ FIM: {func_name} ================\n")
|
| 64 |
+
|
| 65 |
+
return result
|
| 66 |
+
else:
|
| 67 |
+
# Se o log não estiver em modo DEBUG, executa a função sem nenhum overhead.
|
| 68 |
+
return func(*args, **kwargs)
|
| 69 |
+
|
| 70 |
+
return wrapper
|