ErrorIntelligence.Core 1.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package ErrorIntelligence.Core --version 1.0.0
                    
NuGet\Install-Package ErrorIntelligence.Core -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="ErrorIntelligence.Core" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ErrorIntelligence.Core" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="ErrorIntelligence.Core" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add ErrorIntelligence.Core --version 1.0.0
                    
#r "nuget: ErrorIntelligence.Core, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package ErrorIntelligence.Core@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=ErrorIntelligence.Core&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=ErrorIntelligence.Core&version=1.0.0
                    
Install as a Cake Tool

Error Intelligence SDK

SDK para .NET que intercepta erros via ILogger e middleware ASP.NET Core, normaliza em um ErrorEvent e publica em uma fila. Um Orchestrator (Phase 2) consome a fila e roteia para agentes especializados que diagnosticam e tentam remediar o problema automaticamente.

Arquitetura

APLICAÇÃO
   │
   ├── com catch  → logger.LogError(ex, ...) → SDK (ILoggerProvider)
   └── sem catch  → Middleware → SDK
                         │
                         ▼
                   ErrorEvent (normalizado + enriquecido)
                         │
                         ▼
                IErrorPublisher (abstração)
                         │
                         ▼
              Azure Service Bus (queue)
                         │
                         ▼
                   ORCHESTRATOR          ← Phase 2
                         │
             ┌───────────┼───────────┐
             ▼           ▼           ▼
          DB Agent   Code Agent  Infra Agent

Princípio central: o SDK é burro — só captura e publica. A inteligência fica no Orchestrator e nos Agentes. A aplicação nunca quebra se a fila estiver offline.


Projetos

Projeto Responsabilidade
ErrorIntelligence.Core Modelos (ErrorEvent), interfaces (IErrorPublisher), logger provider
ErrorIntelligence.AspNetCore Middleware + extensões de DI para APIs ASP.NET Core
ErrorIntelligence.Publisher.ServiceBus Publisher concreto para Azure Service Bus (Polly retry + circuit breaker)
ErrorIntelligence.Tests Testes unitários (xUnit + Moq)

Instalação

Requisitos: .NET 8 ou superior

# Core + ASP.NET Core
dotnet add package ErrorIntelligence.AspNetCore

# Publisher (Azure Service Bus)
dotnet add package ErrorIntelligence.Publisher.ServiceBus

Como usar

Setup via appsettings.json (recomendado)

Adicione a seção no arquivo de configuração:

{
  "ErrorIntelligence": {
    "ServiceName": "order-service",
    "Environment": "production",
    "ServiceBus": {
      "FullyQualifiedNamespace": "mynamespace.servicebus.windows.net",
      "QueueOrTopicName": "error-intelligence"
    }
  }
}

Para dev local sem Managed Identity, substitua FullyQualifiedNamespace por ConnectionString.

No Program.cs, apenas três linhas:

builder.Services.AddErrorIntelligence(builder.Configuration);
builder.Services.AddServiceBusErrorPublisher(builder.Configuration);

app.UseErrorIntelligence(); // deve vir antes dos outros middlewares

Pronto. Zero código de configuração — tudo vem do appsettings.json.


Setup via código (alternativa explícita)

// Managed Identity (produção)
builder.Services.AddErrorIntelligence(options =>
{
    options.ServiceName = "order-service";
    options.Environment = "production";
});

builder.Services.AddServiceBusErrorPublisher(options =>
{
    options.FullyQualifiedNamespace = "mynamespace.servicebus.windows.net";
    options.QueueOrTopicName        = "error-intelligence";
});

// OU Connection String (dev local)
// options.ConnectionString = "Endpoint=sb://...";

app.UseErrorIntelligence();

2. Código de aplicação — zero mudanças

O SDK funciona sem alterar nenhum catch existente:

// Capturado via ILogger
try
{
    await orderService.ProcessAsync(orderId);
}
catch (Exception ex)
{
    logger.LogError(ex, "Error processing order {OrderId}", orderId);
    throw;
}

// Exceções sem catch são capturadas automaticamente pelo middleware

ErrorEvent — contrato da mensagem

Cada erro publicado na fila tem o seguinte formato:

{
  "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "timestamp": "2026-08-28T14:32:00.000Z",
  "service": "order-service",
  "environment": "production",
  "host": "pod-xyz-123",
  "severity": "Error",
  "exceptionType": "System.Data.SqlClient.SqlException",
  "message": "Error processing order 42",
  "stackTrace": "...",
  "innerExceptionType": null,
  "innerExceptionMessage": null,
  "traceId": "00-abc123-def456-00",
  "correlationId": "corr-789",
  "request": {
    "method": "POST",
    "path": "/api/orders",
    "queryString": null,
    "statusCode": null,
    "userAgent": "..."
  },
  "context": {
    "OrderId": "42",
    "UserId": "user-99"
  }
}

Resiliência

O publisher do Service Bus não quebra a aplicação em nenhuma circunstância:

Cenário Comportamento
Fila offline / timeout Polly faz retry (exponencial + jitter, padrão: 3 tentativas)
Muitas falhas consecutivas Circuit breaker abre (padrão: 60s). Evento descartado com LogWarning local
Publisher lança exception Capturada internamente — aplicação continua normalmente

Configuração de resiliência

builder.Services.AddServiceBusErrorPublisher(options =>
{
    options.FullyQualifiedNamespace          = "mynamespace.servicebus.windows.net";
    options.QueueOrTopicName                 = "error-intelligence";
    options.MaxRetryAttempts                 = 5;   // padrão: 3
    options.CircuitBreakerBreakDurationSeconds = 120; // padrão: 60
});

Permissões — Managed Identity

O SDK não tem identidade própria. Ele usa a identidade da aplicação que o hospeda via DefaultAzureCredential. Portanto, quem precisa ter permissão é a aplicação, não o SDK.

Responsabilidades

Quem O quê
SDK Chama DefaultAzureCredential — zero config de identidade
Aplicação Habilita Managed Identity no recurso Azure (App Service, Container Apps, AKS, etc.)
Infra / DevOps Atribui a role Azure Service Bus Data Sender à identidade da aplicação

Como DefaultAzureCredential resolve a identidade

Em produção no Azure, pega automaticamente a Managed Identity do host. Localmente, usa az login. A ordem de tentativa é:

1. EnvironmentCredential      → variáveis AZURE_CLIENT_ID / AZURE_CLIENT_SECRET
2. WorkloadIdentityCredential → AKS com Workload Identity
3. ManagedIdentityCredential  → App Service / Container Apps / VM / AKS pod
4. VisualStudioCredential     → dev local via Visual Studio
5. AzureCliCredential         → dev local via az login  ← mais comum
6. AzurePowerShellCredential  → dev local via Connect-AzAccount

Atribuindo a role (infra / DevOps)

# ID do namespace do Service Bus
$sbId = az servicebus namespace show \
  --name mynamespace \
  --resource-group meu-rg \
  --query id -o tsv

# Principal ID da Managed Identity da aplicação (exemplo: App Service)
$principalId = az webapp identity show \
  --name minha-api \
  --resource-group meu-rg \
  --query principalId -o tsv

# Atribuir role no namespace inteiro
az role assignment create \
  --assignee $principalId \
  --role "Azure Service Bus Data Sender" \
  --scope $sbId

# OU somente na fila específica (mais restritivo — recomendado)
az role assignment create \
  --assignee $principalId \
  --role "Azure Service Bus Data Sender" \
  --scope "$sbId/queues/error-intelligence"

Dev local com az login

az login
az account set --subscription <sua-subscription>

O DefaultAzureCredential usa suas credenciais do CLI. Certifique-se de que seu usuário também tem a role Azure Service Bus Data Sender, ou use ConnectionString no appsettings.Development.json:

{
  "ErrorIntelligence": {
    "ServiceBus": {
      "ConnectionString": "Endpoint=sb://mynamespace.servicebus.windows.net/;SharedAccessKeyName=..."
    }
  }
}

O .NET carrega o Development por cima do appsettings.json base quando ASPNETCORE_ENVIRONMENT=Development — em produção o Managed Identity prevalece automaticamente.


Deduplicação

Quando um catch chama logger.LogError(ex, ...) e depois faz throw, o SDK usa AsyncLocal para marcar que o erro já foi publicado. O middleware detecta essa flag e não republica o mesmo erro.

Service throw
   │
   ├── catch → logger.LogError → SDK publica → [flag: publicado]
   │
   └── throw → middleware → [flag detectada] → SKIP (sem duplicata)

Workers e Console Apps

Para aplicações sem HTTP (Worker Services, Console), instale apenas o Core:

// Sem UseErrorIntelligence() — o middleware é só para HTTP
builder.Services.AddErrorIntelligence(options => { ... });
builder.Services.AddServiceBusErrorPublisher(options => { ... });

O ILogger continuará interceptando LogError e LogCritical normalmente. Para capturar exceções não tratadas em workers:

AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
{
    // publisher pode ser resolvido via DI e chamado aqui
};

Roadmap

Phase 1 — SDK (concluída ✅)

  • ILoggerProvider intercepta LogError / LogCritical
  • Middleware captura exceções sem catch
  • ErrorEvent normalizado com contexto rico
  • Publisher Azure Service Bus com Polly (retry + circuit breaker)
  • Managed Identity + Connection String
  • Deduplicação via AsyncLocal
  • 13 testes unitários

Phase 2 — Orchestrator

  • Worker Service que consome a fila
  • Classificação por tipo de exceção
  • Interface IErrorAgent (chain-of-responsibility)
  • Roteamento para agente especializado

Phase 3 — Agentes Especializados

  • DB AgentSqlException, DbException
  • Infrastructure AgentTimeoutException, TaskCanceledException
  • Integration AgentHttpRequestException 5xx
  • Code AgentNullReferenceException, ArgumentException
  • LLM Router — classificação inteligente para erros desconhecidos (Azure OpenAI)

Testes

dotnet test
Passed: 13 / 13
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on ErrorIntelligence.Core:

Package Downloads
ErrorIntelligence.AspNetCore

ASP.NET Core integration for ErrorIntelligence SDK. Provides middleware and DI extensions to capture unhandled exceptions automatically.

ErrorIntelligence.Publisher.ServiceBus

Azure Service Bus publisher for ErrorIntelligence SDK. Publishes ErrorEvents to a Service Bus queue or topic with Polly v8 retry and circuit breaker. Supports Managed Identity and Connection String.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.1 120 8/28/2026
1.0.3 121 8/28/2026
1.0.2 121 8/28/2026
1.0.1 117 8/28/2026
1.0.0 122 8/28/2026