# Mentors Event Hub





Sistema centralizado de logging de eventos e exceções com suporte para Azure Service Bus.
## 🚀 Instalação
### PyPI (Público)
```bash
pip install mentors-event-hub
```
### Desenvolvimento
```bash
git clone https://github.com/mentorstec/mentors-event-hub.git
cd mentors-event-hub
pip install -e ".[dev]"
```
## 📋 Configuração
Defina as variáveis de ambiente:
```bash
export AZURE_SERVICE_BUS_CONNECTION_STRING="Endpoint=sb://..."
export AZURE_SERVICE_BUS_QUEUE_NAME="events" # opcional, default: "events"
```
## 🎯 Uso Rápido
### Client Direto (Recomendado)
```python
from mentors_event_hub import EventHubClient
# Criar client
client = EventHubClient.create_azure_client("meu-projeto", 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)
```python
from mentors_event_hub 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:
```json
{
"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
```python
from mentors_event_hub.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
```bash
# Executar testes
pytest tests/ -v --cov=mentors_event_hub
# Lint
black mentors_event_hub/
flake8 mentors_event_hub/
mypy mentors_event_hub/
```
## 🚀 Deploy
### Desenvolvimento
```bash
# 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):**
```bash
# 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:**
```bash
# Release completo (testes + build + upload)
make release
# Para TestPyPI primeiro (recomendado)
make release-test
```
**Upload manual:**
```bash
# Apenas upload (se o build já foi feito)
make upload # PyPI
make upload-test # TestPyPI
```
## 📝 Exemplos Avançados
### Contexto Customizado
```python
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
```python
import sys
from mentors_event_hub import EventHubClient
client = EventHubClient.create_azure_client("meu-app", "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
```python
client = EventHubClient.create_azure_client(
project="meu-projeto",
layer="service",
connection_string="sua-connection-string",
queue_name="eventos-customizados"
)
```
### Environment Variables
- `AZURE_SERVICE_BUS_CONNECTION_STRING` - String de conexão (obrigatória)
- `AZURE_SERVICE_BUS_QUEUE_NAME` - Nome da fila (opcional, default: "events")
## 📄 Licença
MIT License - veja [LICENSE](LICENSE) para detalhes.
## 🤝 Contribuindo
1. Fork o projeto
2. Crie sua feature branch (`git checkout -b feature/nova-feature`)
3. Commit suas mudanças (`git commit -m 'Add nova feature'`)
4. Push para a branch (`git push origin feature/nova-feature`)
5. Abra um Pull Request
## 📞 Suporte
- **Email**: diego@mentorstec.com.br
- **Issues**: [GitHub Issues](https://github.com/mentorstec/mentors-event-hub/issues)
Raw data
{
"_id": null,
"home_page": null,
"name": "mentors-event-hub",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": "azure, event-hub, exceptions, logging, monitoring",
"author": null,
"author_email": "Mentorstec <diego@mentorstec.com.br>",
"download_url": "https://files.pythonhosted.org/packages/09/df/c1670d3d9c7879d78926cdd9d824d76b1c660d7807273bf660dce6eb5036/mentors_event_hub-0.1.3.tar.gz",
"platform": null,
"description": "# Mentors Event Hub\n\n\n\n\n\n\n\nSistema centralizado de logging de eventos e exce\u00e7\u00f5es com suporte para Azure Service Bus.\n\n## \ud83d\ude80 Instala\u00e7\u00e3o\n\n### PyPI (P\u00fablico)\n```bash\npip install mentors-event-hub\n```\n\n### Desenvolvimento\n```bash\ngit clone https://github.com/mentorstec/mentors-event-hub.git\ncd mentors-event-hub\npip install -e \".[dev]\"\n```\n\n## \ud83d\udccb Configura\u00e7\u00e3o\n\nDefina as vari\u00e1veis de ambiente:\n\n```bash\nexport AZURE_SERVICE_BUS_CONNECTION_STRING=\"Endpoint=sb://...\"\nexport AZURE_SERVICE_BUS_QUEUE_NAME=\"events\" # opcional, default: \"events\"\n```\n\n## \ud83c\udfaf Uso R\u00e1pido\n\n### Client Direto (Recomendado)\n\n```python\nfrom mentors_event_hub import EventHubClient\n\n# Criar client\nclient = EventHubClient.create_azure_client(\"meu-projeto\", layer=\"web\")\n\n# Enviar evento\nclient.send_event(\n event_type=\"USER_LOGIN\",\n message=\"Usu\u00e1rio fez login\",\n object=\"auth_service\",\n tags=[\"auth\", \"success\"],\n user_id=123\n)\n\n# Capturar erros automaticamente\n@client.capture_errors(\"payment_process\")\ndef process_payment(amount):\n if amount <= 0:\n raise ValueError(\"Invalid amount\")\n return {\"status\": \"success\"}\n```\n\n### Fun\u00e7\u00f5es Globais (Simples)\n\n```python\nfrom mentors_event_hub import setup_global_hub, send_event, capture_errors\n\n# Configurar uma vez\nsetup_global_hub(\"meu-projeto\", layer=\"api\")\n\n# Usar em qualquer lugar\nsend_event(event_type=\"INFO\", message=\"Sistema iniciado\")\n\n@capture_errors(\"critical_function\")\ndef my_function():\n # Erros s\u00e3o capturados automaticamente\n raise Exception(\"Something went wrong\")\n```\n\n## \ud83d\udcca Estrutura do Payload\n\nTodos os eventos seguem esta estrutura:\n\n```json\n{\n \"project\": \"meu-projeto\",\n \"layer\": \"web\",\n \"message\": \"Usu\u00e1rio fez login\",\n \"obs\": \"\",\n \"timestamp\": \"2025-01-07T10:30:45.123456Z\",\n \"event_type\": \"USER_LOGIN\", \n \"object\": \"auth_service\",\n \"tags\": [\"auth\", \"success\"]\n}\n```\n\n## \ud83c\udfd7\ufe0f Arquitetura\n\nO sistema usa o **Repository Pattern** para m\u00e1xima flexibilidade:\n\n```\n\u251c\u2500\u2500 EventRepository (Interface)\n\u251c\u2500\u2500 AzureServiceBusRepository (Implementa\u00e7\u00e3o) \n\u251c\u2500\u2500 EventHubClient (Factory + API)\n\u2514\u2500\u2500 Fun\u00e7\u00f5es Globais (Compatibilidade)\n```\n\n### Adicionando Novos Provedores\n\n```python\nfrom mentors_event_hub.repository.event_repository import EventRepository\n\nclass CustomRepository(EventRepository):\n def event_handler(self, **kwargs):\n payload = self.build_payload(**kwargs)\n # Sua implementa\u00e7\u00e3o aqui\n self.send_to_custom_service(payload)\n```\n\n## \ud83e\uddea Testes\n\n```bash\n# Executar testes\npytest tests/ -v --cov=mentors_event_hub\n\n# Lint\nblack mentors_event_hub/\nflake8 mentors_event_hub/\nmypy mentors_event_hub/\n```\n\n## \ud83d\ude80 Deploy\n\n### Desenvolvimento\n```bash\n# Instalar depend\u00eancias de desenvolvimento\nmake dev-install\n\n# Executar testes\nmake test\n\n# Linting e formata\u00e7\u00e3o\nmake lint\nmake format\n\n# Build local\nmake build\n```\n\n### Release para PyPI\n\n**Configura\u00e7\u00e3o (uma vez):**\n```bash\n# Configure seu token do PyPI\nexport PYPI_TOKEN=pypi-AgE...seu-token-aqui\n\n# Para TestPyPI (opcional)\nexport PYPI_TEST_TOKEN=pypi-AgE...seu-token-testpypi-aqui\n```\n\n**Release autom\u00e1tico:**\n```bash\n# Release completo (testes + build + upload)\nmake release\n\n# Para TestPyPI primeiro (recomendado)\nmake release-test\n```\n\n**Upload manual:**\n```bash\n# Apenas upload (se o build j\u00e1 foi feito)\nmake upload # PyPI\nmake upload-test # TestPyPI\n```\n\n## \ud83d\udcdd Exemplos Avan\u00e7ados\n\n### Contexto Customizado\n```python\nclient.send_event(\n event_type=\"BUSINESS_ERROR\",\n message=\"Pedido inv\u00e1lido\",\n obs=\"Cliente tentou criar pedido sem itens\",\n object=\"order_service\",\n tags=[\"validation\", \"business\"],\n order_id=\"12345\",\n customer_id=\"67890\"\n)\n```\n\n### Handler de Erros Global\n```python\nimport sys\nfrom mentors_event_hub import EventHubClient\n\nclient = EventHubClient.create_azure_client(\"meu-app\", \"global\")\n\ndef global_exception_handler(exc_type, exc_value, exc_traceback):\n import traceback\n client.send_event(\n event_type=\"CRITICAL_ERROR\",\n message=str(exc_value),\n obs=\"\".join(traceback.format_exception(exc_type, exc_value, exc_traceback)),\n object=\"uncaught_exception\",\n tags=[\"critical\", exc_type.__name__]\n )\n sys.__excepthook__(exc_type, exc_value, exc_traceback)\n\nsys.excepthook = global_exception_handler\n```\n\n## \ud83d\udd27 Configura\u00e7\u00f5es Avan\u00e7adas\n\n### Client Customizado\n```python\nclient = EventHubClient.create_azure_client(\n project=\"meu-projeto\",\n layer=\"service\", \n connection_string=\"sua-connection-string\",\n queue_name=\"eventos-customizados\"\n)\n```\n\n### Environment Variables\n- `AZURE_SERVICE_BUS_CONNECTION_STRING` - String de conex\u00e3o (obrigat\u00f3ria)\n- `AZURE_SERVICE_BUS_QUEUE_NAME` - Nome da fila (opcional, default: \"events\")\n\n## \ud83d\udcc4 Licen\u00e7a\n\nMIT License - veja [LICENSE](LICENSE) para detalhes.\n\n## \ud83e\udd1d Contribuindo\n\n1. Fork o projeto\n2. Crie sua feature branch (`git checkout -b feature/nova-feature`)\n3. Commit suas mudan\u00e7as (`git commit -m 'Add nova feature'`)\n4. Push para a branch (`git push origin feature/nova-feature`)\n5. Abra um Pull Request\n\n## \ud83d\udcde Suporte\n\n- **Email**: diego@mentorstec.com.br\n- **Issues**: [GitHub Issues](https://github.com/mentorstec/mentors-event-hub/issues)\n",
"bugtrack_url": null,
"license": null,
"summary": "Event hub for centralized exception logging and monitoring",
"version": "0.1.3",
"project_urls": {
"Documentation": "https://github.com/Mentorstec/mentors-event-hub#readme",
"Homepage": "https://github.com/Mentorstec/mentors-event-hub",
"Issues": "https://github.com/Mentorstec/mentors-event-hub/issues",
"Repository": "https://github.com/Mentorstec/mentors-event-hub"
},
"split_keywords": [
"azure",
" event-hub",
" exceptions",
" logging",
" monitoring"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "d97cddd61f104f588a8551754be66b005e04461ffacfd49b5bf2ac65a100bf48",
"md5": "a609bbcac5fcf6855cb8b8fde8df7f0f",
"sha256": "f11962ceecc0aea677537f4700068cee6355c1e2112d520065607f9fc9ea09a8"
},
"downloads": -1,
"filename": "mentors_event_hub-0.1.3-py3-none-any.whl",
"has_sig": false,
"md5_digest": "a609bbcac5fcf6855cb8b8fde8df7f0f",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 9873,
"upload_time": "2025-08-08T00:37:20",
"upload_time_iso_8601": "2025-08-08T00:37:20.742331Z",
"url": "https://files.pythonhosted.org/packages/d9/7c/ddd61f104f588a8551754be66b005e04461ffacfd49b5bf2ac65a100bf48/mentors_event_hub-0.1.3-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "09dfc1670d3d9c7879d78926cdd9d824d76b1c660d7807273bf660dce6eb5036",
"md5": "faa9a571761383788a0bc5ab7df12699",
"sha256": "ea9a90375b5c3fbbbbd82dd2fda869ec9a3cbbfdab8957fde4b6bc32634e3858"
},
"downloads": -1,
"filename": "mentors_event_hub-0.1.3.tar.gz",
"has_sig": false,
"md5_digest": "faa9a571761383788a0bc5ab7df12699",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 19194,
"upload_time": "2025-08-08T00:37:21",
"upload_time_iso_8601": "2025-08-08T00:37:21.853459Z",
"url": "https://files.pythonhosted.org/packages/09/df/c1670d3d9c7879d78926cdd9d824d76b1c660d7807273bf660dce6eb5036/mentors_event_hub-0.1.3.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-08 00:37:21",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "Mentorstec",
"github_project": "mentors-event-hub#readme",
"github_not_found": true,
"lcname": "mentors-event-hub"
}