Mentorstec - centralized event logging and monitoring
Project description
Mentorstec
Sistema centralizado de logging de eventos e exceções com suporte para Azure Service Bus.
🚀 Instalação
PyPI (Público)
pip install mentorstec
Desenvolvimento
git clone https://github.com/mentorstec/mentorstec.git
cd mentorstec
pip install -e ".[dev]"
📋 Configuração
Defina as variáveis de ambiente:
export AZURE_SERVICE_BUS_CONNECTION_STRING="Endpoint=sb://..."
🎯 Uso Rápido
Client Direto (Recomendado)
from mentorstec import EventHubClient
# Criar client
client = EventHubClient.create_azure_client("meu-projeto", "events", layer="web")
# Enviar evento
client.send_event(
event_type="USER_LOGIN",
message="Usuário fez login",
object="auth_service",
tags=["auth", "success"],
user_id=123
)
# Capturar erros automaticamente
@client.capture_errors("payment_process")
def process_payment(amount):
if amount <= 0:
raise ValueError("Invalid amount")
return {"status": "success"}
Funções Globais (Simples)
from mentorstec import setup_global_hub, send_event, capture_errors
# Configurar uma vez
setup_global_hub("meu-projeto", layer="api")
# Usar em qualquer lugar
send_event(event_type="INFO", message="Sistema iniciado")
@capture_errors("critical_function")
def my_function():
# Erros são capturados automaticamente
raise Exception("Something went wrong")
📊 Estrutura do Payload
Todos os eventos seguem esta estrutura:
{
"project": "meu-projeto",
"layer": "web",
"message": "Usuário fez login",
"obs": "",
"timestamp": "2025-01-07T10:30:45.123456Z",
"event_type": "USER_LOGIN",
"object": "auth_service",
"tags": ["auth", "success"]
}
🏗️ Arquitetura
O sistema usa o Repository Pattern para máxima flexibilidade:
├── EventRepository (Interface)
├── AzureServiceBusRepository (Implementação)
├── EventHubClient (Factory + API)
└── Funções Globais (Compatibilidade)
Adicionando Novos Provedores
from mentorstec.repository.event_repository import EventRepository
class CustomRepository(EventRepository):
def event_handler(self, **kwargs):
payload = self.build_payload(**kwargs)
# Sua implementação aqui
self.send_to_custom_service(payload)
🧪 Testes
# Executar testes
pytest tests/ -v --cov=mentorstec
# Lint
black mentorstec/
flake8 mentorstec/
mypy mentorstec/
🚀 Deploy
Desenvolvimento
# Instalar dependências de desenvolvimento
make dev-install
# Executar testes
make test
# Linting e formatação
make lint
make format
# Build local
make build
Release para PyPI
Configuração (uma vez):
# Configure seu token do PyPI
export PYPI_TOKEN=pypi-AgE...seu-token-aqui
# Para TestPyPI (opcional)
export PYPI_TEST_TOKEN=pypi-AgE...seu-token-testpypi-aqui
Release automático:
# Release completo (testes + build + upload)
make release
# Para TestPyPI primeiro (recomendado)
make release-test
Upload manual:
# Apenas upload (se o build já foi feito)
make upload # PyPI
make upload-test # TestPyPI
📝 Exemplos Avançados
Contexto Customizado
client.send_event(
event_type="BUSINESS_ERROR",
message="Pedido inválido",
obs="Cliente tentou criar pedido sem itens",
object="order_service",
tags=["validation", "business"],
order_id="12345",
customer_id="67890"
)
Handler de Erros Global
import sys
from mentorstec import EventHubClient
client = EventHubClient.create_azure_client("meu-app", "global-events", "global")
def global_exception_handler(exc_type, exc_value, exc_traceback):
import traceback
client.send_event(
event_type="CRITICAL_ERROR",
message=str(exc_value),
obs="".join(traceback.format_exception(exc_type, exc_value, exc_traceback)),
object="uncaught_exception",
tags=["critical", exc_type.__name__]
)
sys.__excepthook__(exc_type, exc_value, exc_traceback)
sys.excepthook = global_exception_handler
🔧 Configurações Avançadas
Client Customizado
client = EventHubClient.create_azure_client(
project="meu-projeto",
queue_name="eventos-customizados",
layer="service",
connection_string="sua-connection-string"
)
Environment Variables
AZURE_SERVICE_BUS_CONNECTION_STRING- String de conexão (obrigatória)
📄 Licença
MIT License - veja LICENSE para detalhes.
🤝 Contribuindo
- Fork o projeto
- Crie sua feature branch (
git checkout -b feature/nova-feature) - Commit suas mudanças (
git commit -m 'Add nova feature') - Push para a branch (
git push origin feature/nova-feature) - Abra um Pull Request
📞 Suporte
- Email: diego@mentorstec.com.br
- Issues: GitHub Issues
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mentorstec-0.1.3.tar.gz.
File metadata
- Download URL: mentorstec-0.1.3.tar.gz
- Upload date:
- Size: 28.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b201228c292da00bede0e08f47d553487e8b213e4a5f5b17a1d888fca972cbe7
|
|
| MD5 |
ad996d046526f1986290bc15856082d0
|
|
| BLAKE2b-256 |
997afd18493b6a5156e4ada54f46de119c7298900d7c264c12b74b05a5eade06
|
File details
Details for the file mentorstec-0.1.3-py3-none-any.whl.
File metadata
- Download URL: mentorstec-0.1.3-py3-none-any.whl
- Upload date:
- Size: 20.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
43b0d2a1d8e8d87bf460ea77d489184f90032f47073c97f4b8a1e64387645196
|
|
| MD5 |
d4ad95edd303549467d19c50b8aa858d
|
|
| BLAKE2b-256 |
8642073793d27d2ed89190a95347efda057bfb0df789f4430e117c0c5da90d8c
|