BR.JCode.LogFlow.Owin
1.0.0-preview.2
dotnet add package BR.JCode.LogFlow.Owin --version 1.0.0-preview.2
NuGet\Install-Package BR.JCode.LogFlow.Owin -Version 1.0.0-preview.2
<PackageReference Include="BR.JCode.LogFlow.Owin" Version="1.0.0-preview.2" />
<PackageVersion Include="BR.JCode.LogFlow.Owin" Version="1.0.0-preview.2" />
<PackageReference Include="BR.JCode.LogFlow.Owin" />
paket add BR.JCode.LogFlow.Owin --version 1.0.0-preview.2
#r "nuget: BR.JCode.LogFlow.Owin, 1.0.0-preview.2"
#:package BR.JCode.LogFlow.Owin@1.0.0-preview.2
#addin nuget:?package=BR.JCode.LogFlow.Owin&version=1.0.0-preview.2&prerelease
#tool nuget:?package=BR.JCode.LogFlow.Owin&version=1.0.0-preview.2&prerelease
<p align="center"> <img src="https://img.shields.io/badge/BR.JCode-LogFlow-blueviolet?style=for-the-badge&logo=dotnet&logoColor=white" alt="BR.JCode LogFlow" /> </p>
<h1 align="center">BR.JCode.LogFlow</h1>
<p align="center"> <strong>Dashboard de logs empresarial para .NET</strong><br/> Captura, persiste, alerta e exibe logs estruturados em tempo real.<br/> Zero alteracoes no codigo host. Plug & Play. </p>
<p align="center"> <a href="https://github.com/JCodeArch/LogFlow/actions"><img src="https://img.shields.io/github/actions/workflow/status/JCodeArch/LogFlow/dotnet.yml?branch=main&style=flat-square&logo=github&label=CI" alt="CI" /></a> <a href="https://www.nuget.org/packages/BR.JCode.LogFlow"><img src="https://img.shields.io/nuget/v/BR.JCode.LogFlow?style=flat-square&logo=nuget&label=NuGet&color=004880" alt="NuGet" /></a> <a href="https://www.nuget.org/packages/BR.JCode.LogFlow"><img src="https://img.shields.io/nuget/dt/BR.JCode.LogFlow?style=flat-square&logo=nuget&label=Downloads&color=green" alt="Downloads" /></a> <a href="https://github.com/JCodeArch/LogFlow/blob/main/LICENSE"><img src="https://img.shields.io/github/license/JCodeArch/LogFlow?style=flat-square&logo=opensourceinitiative&logoColor=white&label=Licen%C3%A7a" alt="License" /></a> <a href="https://github.com/JCodeArch/LogFlow"><img src="https://img.shields.io/github/stars/JCodeArch/LogFlow?style=flat-square&logo=github&label=Stars" alt="Stars" /></a> <a href="https://github.com/JCodeArch/LogFlow/issues"><img src="https://img.shields.io/github/issues/JCodeArch/LogFlow?style=flat-square&logo=github&label=Issues" alt="Issues" /></a> </p>
<p align="center"> <img src="https://img.shields.io/badge/.NET_Standard_2.0-512BD4?style=flat-square&logo=dotnet&logoColor=white" alt=".NET Standard 2.0" /> <img src="https://img.shields.io/badge/.NET_6.0-512BD4?style=flat-square&logo=dotnet&logoColor=white" alt=".NET 6.0" /> <img src="https://img.shields.io/badge/.NET_8.0_LTS-512BD4?style=flat-square&logo=dotnet&logoColor=white" alt=".NET 8.0" /> <img src="https://img.shields.io/badge/.NET_9.0-512BD4?style=flat-square&logo=dotnet&logoColor=white" alt=".NET 9.0" /> <img src="https://img.shields.io/badge/.NET_Framework_4.6.1+-512BD4?style=flat-square&logo=dotnet&logoColor=white" alt=".NET Framework" /> </p>
<p align="center"> <img src="https://img.shields.io/badge/SQLite-003B57?style=flat-square&logo=sqlite&logoColor=white" alt="SQLite" /> <img src="https://img.shields.io/badge/SQL_Server-CC2927?style=flat-square&logo=microsoftsqlserver&logoColor=white" alt="SQL Server" /> <img src="https://img.shields.io/badge/PostgreSQL-4169E1?style=flat-square&logo=postgresql&logoColor=white" alt="PostgreSQL" /> <img src="https://img.shields.io/badge/SSE_Realtime-FF6600?style=flat-square&logo=lightning&logoColor=white" alt="SSE" /> <img src="https://img.shields.io/badge/SMTP_Email-EA4335?style=flat-square&logo=gmail&logoColor=white" alt="Email" /> <img src="https://img.shields.io/badge/Microsoft_Teams-6264A7?style=flat-square&logo=microsoftteams&logoColor=white" alt="Teams" /> <img src="https://img.shields.io/badge/Webhook-181717?style=flat-square&logo=webhook&logoColor=white" alt="Webhook" /> </p>
Indice
- Sobre
- Funcionalidades
- Requisitos
- Instalacao
- Quick Start
- Configuracao Completa
- NET Framework OWIN
- Dashboard Web
- Sistema de Alertas
- Notificacoes
- Backup e Retencao
- Correlation ID
- Providers de Banco
- Worker Service / Console
- Arquitetura
- Contribuindo
- Licenca
🔎 Sobre
BR.JCode.LogFlow e uma biblioteca de logging empresarial para .NET que se integra nativamente ao ILogger<T>. Basta registrar o servico via DI e todos os logs da aplicacao sao capturados, persistidos em SQLite (ou SQL Server / PostgreSQL), exibidos em um dashboard web embarcado com streaming em tempo real via SSE, e opcionalmente disparam alertas por Email, Microsoft Teams ou Webhook.
Zero alteracoes no codigo host - se voce ja usa
ILogger<T>, o BR.JCode.LogFlow captura tudo automaticamente.
✨ Funcionalidades
| Recurso | Descricao |
|---|---|
| Dashboard Web Embarcado | Painel responsivo com graficos, filtros e tema dark/light |
| Streaming em Tempo Real | Server-Sent Events (SSE) para logs ao vivo |
| Alertas Inteligentes | Regras com threshold, janela temporal e cooldown |
| 3 Canais de Notificacao | Email SMTP, Microsoft Teams (Adaptive Card), Webhook generico |
| Retry com Backoff | Tentativas automaticas com backoff exponencial (2s, 4s, 8s...) |
| Backup Automatico | Backups comprimidos com GZip (~90% compressao) e rotacao |
| Purge Automatico | Limpeza automatica de logs antigos por retencao |
| Correlation ID | Rastreamento de requests distribuidos |
| Multi-Usuario | Autenticacao com roles (Admin/Viewer) e sessoes seguras |
| Multi-Database | SQLite (builtin), SQL Server, PostgreSQL |
| Multi-Target | netstandard2.0, net6.0, net8.0, net9.0 |
| Zero CDN | Dashboard 100% embarcado (HTML + Chart.js) - funciona offline |
📋 Requisitos
| Target Framework | Plataforma | Dashboard | Notificacoes |
|---|---|---|---|
netstandard2.0 |
.NET Framework 4.6.1+, .NET Core 2.0+ | OWIN Middleware (BR.JCode.LogFlow.Owin) | |
net6.0 |
.NET 6 | SSE + Dashboard completo | Email, Teams, Webhook |
net8.0 |
.NET 8 LTS | SSE + Dashboard completo | Email, Teams, Webhook |
net9.0 |
.NET 9 | SSE + Dashboard completo | Email, Teams, Webhook |
Nota: Para o dashboard no .NET Framework, utilize o pacote BR.JCode.LogFlow.Owin. Ele fornece o middleware OWIN compativel com WebAPI 2 e MVC 5.
📦 Instalacao
Pacote principal (SQLite incluso)
dotnet add package BR.JCode.LogFlow
Providers adicionais (opcional)
# SQL Server / Azure SQL
dotnet add package BR.JCode.LogFlow.SqlServer
# PostgreSQL
dotnet add package BR.JCode.LogFlow.PostgreSql
🚀 Quick Start
Adicione 2 linhas ao seu Program.cs:
using BR.JCode.LogFlow;
var builder = WebApplication.CreateBuilder(args);
// 1. Registrar o BR.JCode.LogFlow
builder.Services.AddLogFlow(opt =>
{
opt.ApplicationName = "MinhaApp";
opt.Environment = builder.Environment.EnvironmentName;
});
var app = builder.Build();
// 2. Montar o dashboard
app.UseLogFlow();
app.Run();
Acesse http://localhost:5000/logs no navegador.
Login padrao:
admin/logflow123
⚙️ Configuracao Completa
builder.Services.AddLogFlow(opt =>
{
// --- Identidade ---
// Nome da aplicacao exibido no dashboard e nas notificacoes de alerta
opt.ApplicationName = "MeuServico";
// Ambiente exibido como badge no dashboard (Development, Staging, Production)
opt.Environment = "Production";
// --- Dashboard ---
// Habilita ou desabilita o dashboard web embarcado
opt.EnableDashboard = true; // default: true
// Caminho base do dashboard e de todas as rotas da API REST
opt.DashboardPath = "/logs"; // default: "/logs"
// Titulo exibido na aba do browser e no cabecalho do dashboard
opt.DashboardTitle = "LogFlow"; // default: "LogFlow"
// URL de um logotipo personalizado exibido no dashboard (null = logo padrao)
opt.LogoUrl = null; // default: null
// --- Storage ---
// Caminho do arquivo SQLite. Omita para usar o caminho padrao do SO:
// Windows: %ProgramData%\BR.JCode.LogFlow\logflow.db
// Linux: /var/lib/logflow/logflow.db
opt.DatabasePath = "/var/data/logs.db";
// --- Retencao ---
// Habilita o purge automatico de logs antigos para controlar o tamanho do banco
opt.PurgeEnabled = true; // default: true
// Numero de dias para manter os logs antes de serem excluidos pelo purge
opt.RetentionDays = 30; // default: 7
// Intervalo em horas entre cada execucao do purge automatico
opt.PurgeIntervalHours = 24; // default: 24
// --- Nivel Minimo ---
// Somente logs com nivel >= MinimumLevel serao capturados e persistidos
opt.MinimumLevel = LogLevel.Information; // default: Trace
// --- Categorias Excluidas ---
// Categorias de logger que devem ser ignoradas (evita ruido de frameworks)
opt.ExcludeCategories.Add("Microsoft.AspNetCore");
opt.ExcludeCategories.Add("Microsoft.EntityFrameworkCore");
// --- Pipeline Assincrono ---
// Capacidade maxima do Channel<T> interno; logs excedentes sao descartados
opt.ChannelCapacity = 50_000; // default: 50000
// Numero maximo de logs gravados por batch no SQLite
opt.WriteBatchSize = 50; // default: 50
// Tempo maximo de espera antes de gravar um batch incompleto
opt.WriteBatchTimeout = TimeSpan.FromMilliseconds(500); // default: 500ms
// --- Correlation ID ---
// Extrai o Correlation ID do header HTTP e associa a todos os logs do request
opt.EnableCorrelationId = true;
// Nome do header HTTP de onde o Correlation ID sera lido (ou gerado se ausente)
opt.CorrelationIdHeader = "X-Correlation-Id"; // default
// --- Backup ---
// Habilita backups automaticos do banco SQLite comprimidos com GZip (~90%)
opt.Backup.Enabled = true;
// Intervalo em horas entre cada backup automatico
opt.Backup.IntervalHours = 24; // default: 24
// Numero maximo de arquivos de backup mantidos (os mais antigos sao removidos)
opt.Backup.MaxBackupCount = 7; // default: 7
// Tamanho maximo do banco (em MB) que aciona um backup imediato
opt.Backup.MaxDatabaseSizeMB = 5120; // default: 5120 (5 GB)
// Diretorio onde os backups serao armazenados
opt.Backup.BackupDirectory = "/var/backups/logflow";
// --- Alertas: Email (SMTP) ---
// Servidor SMTP para envio de alertas por e-mail
opt.Alerts.Smtp.Host = "smtp.office365.com";
opt.Alerts.Smtp.Port = 587; // default: 587
opt.Alerts.Smtp.EnableSsl = true; // default: true
opt.Alerts.Smtp.Username = "alerts@empresa.com.br";
opt.Alerts.Smtp.Password = Environment.GetEnvironmentVariable("SMTP_PASS")!;
opt.Alerts.Smtp.FromAddress = "logflow@empresa.com.br";
opt.Alerts.Smtp.FromName = "BR.JCode LogFlow";
// Destinatarios padrao (separados por ; ou ,) — pode ser sobrescrito por regra
opt.Alerts.Smtp.DefaultRecipients = "equipe@empresa.com.br;gestor@empresa.com.br";
// --- Alertas: Microsoft Teams ---
// URL do Incoming Webhook do canal Teams (requer .NET 6.0+)
opt.Alerts.TeamsWebhookUrl = Environment.GetEnvironmentVariable("TEAMS_WEBHOOK");
// --- Alertas: Webhook Generico (Slack, Discord, PagerDuty...) ---
// URL do endpoint HTTP que recebera o payload JSON do alerta
opt.Alerts.WebhookUrl = Environment.GetEnvironmentVariable("WEBHOOK_URL");
// Headers HTTP adicionais enviados com o webhook (ex: autenticacao)
opt.Alerts.WebhookHeaders["Authorization"] = "Bearer my-secret-token";
// --- Retry com Backoff Exponencial ---
// Numero de tentativas de reenvio em caso de falha (backoff: 2s, 4s, 8s...)
opt.Alerts.RetryAttempts = 3; // default: 3
});
var app = builder.Build();
app.UseLogFlow();
app.Run();
🖥️ .NET Framework / OWIN
Para projetos WebAPI 2 / MVC 5 / .NET Framework 4.6.1+, use o pacote OWIN dedicado.
1. Instalacao
dotnet add package BR.JCode.LogFlow
dotnet add package BR.JCode.LogFlow.Owin
Ou via Package Manager Console:
Install-Package BR.JCode.LogFlow
Install-Package BR.JCode.LogFlow.Owin
2. Registro dos servicos (Global.asax.cs ou container DI existente)
using BR.JCode.LogFlow;
using Microsoft.Extensions.DependencyInjection;
// Construa o container de DI
var services = new ServiceCollection();
services.AddLogFlow(opt =>
{
opt.ApplicationName = "MinhaAppLegacy";
opt.Environment = "Production";
// Caminho explicito do banco SQLite (opcional)
opt.DatabasePath = @"C:\ProgramData\MinhaEmpresa\logs.db";
// Retencao de logs
opt.PurgeEnabled = true;
opt.RetentionDays = 30;
opt.PurgeIntervalHours = 24;
// Nivel minimo capturado
opt.MinimumLevel = Microsoft.Extensions.Logging.LogLevel.Information;
// Alertas por Email (opcional)
opt.Alerts.Smtp.Host = "smtp.office365.com";
opt.Alerts.Smtp.Port = 587;
opt.Alerts.Smtp.EnableSsl = true;
opt.Alerts.Smtp.Username = "alerts@empresa.com.br";
opt.Alerts.Smtp.Password = System.Configuration.ConfigurationManager.AppSettings["SmtpPassword"];
opt.Alerts.Smtp.FromAddress = "logflow@empresa.com.br";
opt.Alerts.Smtp.DefaultRecipients = "equipe@empresa.com.br";
});
var serviceProvider = services.BuildServiceProvider();
3. Registrar o ILoggerFactory no seu framework
Se voce usa WebAPI 2 com ILogger<T>:
// Obtem o factory do container e adiciona o provider LogFlow
var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
// Todos os ILogger<T> da aplicacao agora enviam logs para o LogFlow
Se voce usa log4net, NLog ou outro framework legado, adapte um appender/sink que escreva para ILogger<T> ou use o pipeline diretamente.
4. Montar o dashboard OWIN (Startup.cs)
using BR.JCode.LogFlow.Owin;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Owin;
public class Startup
{
public void Configuration(IAppBuilder app)
{
var options = serviceProvider.GetRequiredService<LogFlowOptions>(); // ou crie manualmente
// Monta o dashboard em /logflow
app.UseLogFlow(serviceProvider);
}
}
5. Self-hosted (Console / Windows Service)
using BR.JCode.LogFlow.Owin;
using Microsoft.Owin.Hosting;
class Program
{
static void Main()
{
// Registra servicos
var services = new ServiceCollection();
services.AddLogFlow(opt =>
{
opt.ApplicationName = "MinhaAppLegacy";
opt.Environment = "Production";
opt.DatabasePath = @"C:\ProgramData\MinhaEmpresa\logs.db";
opt.RetentionDays = 30;
});
var sp = services.BuildServiceProvider();
// Inicia o servidor OWIN
var startOptions = new StartOptions();
startOptions.Urls.Add("http://localhost:9000");
startOptions.Urls.Add("http://127.0.0.1:9000");
using (WebApp.Start<Startup>(startOptions))
{
Console.WriteLine("Dashboard disponivel em http://localhost:9000/logflow");
Console.WriteLine("Login: admin / logflow123");
Console.ReadLine();
}
}
}
Nota: Registre
http://localhost:9000ehttp://127.0.0.1:9000com o comandonetshse necessario:netsh http add urlacl url=http://localhost:9000/ user=TODOS netsh http add urlacl url=http://127.0.0.1:9000/ user=TODOS
Opcoes de configuracao completas para .NET Framework
| Opcao | Tipo | Default | Descricao |
|---|---|---|---|
ApplicationName |
string |
"App" |
Nome exibido no dashboard e alertas |
Environment |
string |
"" |
Badge de ambiente (Development / Staging / Production) |
DatabasePath |
string |
%ProgramData%\BR.JCode.LogFlow\logflow.db |
Caminho do arquivo SQLite |
MinimumLevel |
LogLevel |
Trace |
Nivel minimo para capturar logs |
PurgeEnabled |
bool |
true |
Ativa limpeza automatica de logs antigos |
RetentionDays |
int |
7 |
Dias de retencao antes do purge |
PurgeIntervalHours |
int |
24 |
Frequencia do purge em horas |
DashboardTitle |
string |
"LogFlow" |
Titulo exibido no browser |
EnableDashboard |
bool |
true |
Habilita o painel web |
ChannelCapacity |
int |
50000 |
Capacidade maxima do buffer interno |
Alerts.Smtp.* |
— | — | Configuracao de email SMTP |
Backup.Enabled |
bool |
true |
Ativa backup automatico do SQLite |
Backup.MaxBackupCount |
int |
7 |
Numero de backups retidos |
🖥️ Dashboard Web
O dashboard e acessado em /logs (configuravel via DashboardPath).
Recursos do Dashboard
| Funcionalidade | Descricao |
|---|---|
| Logs em Tempo Real | Stream SSE com atualizacao automatica |
| Filtros Avancados | Nivel, categoria, texto, periodo, Correlation ID |
| Graficos | Timeline de logs com Chart.js (dark/light mode) |
| Estatisticas | Contagem por nivel (Trace, Debug, Info, Warning, Error, Critical) |
| Alertas | CRUD completo de regras + teste de notificacao |
| Historico de Alertas | Registro de disparos com badges de status por canal |
| Gerenciamento de Usuarios | Criar, editar, excluir usuarios (Admin only) |
| Backup | Criar, listar, baixar e excluir backups |
| Configuracoes | Purge, armazenamento, informacoes do sistema |
| Tema Dark/Light | Alternancia de tema com persistencia |
| Badge de Ambiente | Indicador visual do ambiente (Dev/Staging/Production) |
| 100% Embarcado | Nenhuma dependencia de CDN - funciona offline |
Autenticacao
O sistema cria automaticamente um usuario admin padrao:
- Usuario:
admin - Senha:
logflow123
Importante: Altere a senha padrao em producao via dashboard ou API.
Roles disponiveis:
| Role | Permissoes |
|---|---|
Admin |
Acesso total: logs, alertas, usuarios, backups, configuracoes |
Viewer |
Somente leitura: logs, estatisticas, alertas (sem editar) |
🚨 Sistema de Alertas
Crie regras de alerta diretamente pelo dashboard ou via API REST.
Anatomia de uma Regra
{
"name": "Erros Criticos em Pagamento",
"enabled": true,
"level": "Error",
"categoryContains": "PaymentService",
"messageContains": "timeout",
"thresholdCount": 5,
"thresholdWindowMinutes": 10,
"cooldownMinutes": 30,
"notifyEmail": true,
"notifyTeams": true,
"notifyWebhook": false,
"emailRecipients": "equipe-pagamento@empresa.com.br"
}
Como Funciona
Log capturado --> Matcher verifica regras ativas
|
v
Threshold atingido? (N logs em X minutos)
|
v
Em cooldown? --> Sim: ignora
|
Nao
v
Dispara notificacao(oes)
/ | \
Email Teams Webhook
\ | /
RetryDecorator (backoff exponencial)
|
v
Registra no historico (sucesso/falha por canal)
📣 Notificacoes
Email (SMTP)
<img src="https://img.shields.io/badge/SMTP-Todos_os_frameworks-success?style=flat-square&logo=gmail&logoColor=white" alt="SMTP" />
opt.Alerts.Smtp.Host = "smtp.office365.com";
opt.Alerts.Smtp.Port = 587;
opt.Alerts.Smtp.EnableSsl = true;
opt.Alerts.Smtp.Username = "alerts@empresa.com.br";
opt.Alerts.Smtp.Password = Environment.GetEnvironmentVariable("SMTP_PASS")!;
opt.Alerts.Smtp.FromAddress = "logflow@empresa.com.br";
opt.Alerts.Smtp.DefaultRecipients = "equipe@empresa.com.br;gestor@empresa.com.br";
- Envia HTML formatado com detalhes do alerta
- Suporta multiplos destinatarios (separados por
;ou,) - Override por regra via
emailRecipients
Microsoft Teams
<img src="https://img.shields.io/badge/Teams-net6.0+-6264A7?style=flat-square&logo=microsoftteams&logoColor=white" alt="Teams" />
opt.Alerts.TeamsWebhookUrl = "https://outlook.office.com/webhook/...";
- Envia Adaptive Card formatado
- Suporta URL override por regra
- Requer .NET 6.0+ (usa
IHttpClientFactory)
Webhook Generico
<img src="https://img.shields.io/badge/Webhook-net6.0+-181717?style=flat-square&logo=webhook&logoColor=white" alt="Webhook" />
Compativel com Slack, Discord, PagerDuty, Opsgenie, ou qualquer endpoint HTTP.
opt.Alerts.WebhookUrl = "https://hooks.slack.com/services/...";
opt.Alerts.WebhookHeaders["Authorization"] = "Bearer meu-token";
Payload enviado (JSON):
{
"ruleName": "Erros Criticos",
"level": "Error",
"message": "Database connection timeout after 30s",
"category": "Services.PaymentService",
"matchCount": 5,
"firedAt": "2026-02-26T14:30:00Z",
"applicationName": "MeuServico",
"environment": "Production"
}
Retry com Backoff Exponencial
Todas as notificacoes sao envolvidas por um RetryNotifierDecorator:
Tentativa 1 --> Falhou --> Aguarda 2s
Tentativa 2 --> Falhou --> Aguarda 4s
Tentativa 3 --> Falhou --> Registra erro no historico
Configuravel via opt.Alerts.RetryAttempts (default: 3).
💾 Backup e Retencao
Backup Automatico
opt.Backup.Enabled = true;
opt.Backup.IntervalHours = 24; // A cada 24h
opt.Backup.MaxBackupCount = 7; // Manter ultimos 7
opt.Backup.MaxDatabaseSizeMB = 5120; // Limite de 5GB
- Backups sao comprimidos com GZip (~90% de compressao)
- Rotacao automatica (remove backups antigos)
- Criar/baixar/excluir backups manualmente pelo dashboard
- Usa
SQLite backup APInativa +Pooling=falsepara evitar file locking
Purge Automatico
opt.PurgeEnabled = true; // Ativado por padrao
opt.RetentionDays = 7; // Manter 7 dias
opt.PurgeIntervalHours = 24; // Executar a cada 24h
🔗 Correlation ID
Rastreie requests distribuidos automaticamente:
opt.EnableCorrelationId = true;
opt.CorrelationIdHeader = "X-Correlation-Id"; // Header HTTP
Quando habilitado:
- O middleware extrai o header
X-Correlation-Idde cada request - Gera um novo ID se nao existir
- Todos os logs daquele request sao marcados com o mesmo Correlation ID
- Filtre no dashboard por Correlation ID para rastrear um request end-to-end
🗄️ Providers de Banco
SQLite (Padrao)
<img src="https://img.shields.io/badge/SQLite-Incluso-003B57?style=flat-square&logo=sqlite&logoColor=white" alt="SQLite" />
Incluso no pacote principal. Sem configuracao adicional.
opt.DatabasePath = "logs/logflow.db";
SQL Server
<img src="https://img.shields.io/badge/SQL_Server-Addon-CC2927?style=flat-square&logo=microsoftsqlserver&logoColor=white" alt="SQL Server" />
dotnet add package BR.JCode.LogFlow.SqlServer
builder.Services.AddLogFlow(opt => { /* ... */ });
builder.Services.AddLogFlowSqlServer("Server=...;Database=LogFlow;...");
PostgreSQL
<img src="https://img.shields.io/badge/PostgreSQL-Addon-4169E1?style=flat-square&logo=postgresql&logoColor=white" alt="PostgreSQL" />
dotnet add package BR.JCode.LogFlow.PostgreSql
builder.Services.AddLogFlow(opt => { /* ... */ });
builder.Services.AddLogFlowPostgreSql("Host=...;Database=logflow;...");
🔧 Worker Service / Console
Para aplicacoes sem ASP.NET Core (Worker Services, Console Apps):
var host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddLogFlow(opt =>
{
opt.EnableDashboard = false; // Sem dashboard
opt.ApplicationName = "WorkerService";
opt.DatabasePath = "logs/worker.db";
opt.MinimumLevel = LogLevel.Warning;
opt.Alerts.Smtp.Host = "smtp.empresa.com.br";
opt.Alerts.Smtp.Username = "alerts@empresa.com.br";
opt.Alerts.Smtp.Password = Environment.GetEnvironmentVariable("SMTP_PASS")!;
});
services.AddHostedService<MeuWorker>();
})
.Build();
await host.RunAsync();
Os logs sao persistidos no SQLite e podem ser visualizados conectando outra aplicacao ASP.NET Core ao mesmo banco.
🏗️ Arquitetura
BR.JCode.LogFlow/
|-- src/BR.JCode.LogFlow/
| |-- Abstractions/ # Interfaces (ILogRepository, IAlertNotifier, etc.)
| |-- Application/ # Logica de negocio (AlertEvaluator, LogFlowProcessor)
| |-- Configuration/ # LogFlowOptions e DTOs de configuracao
| |-- Dashboard/ # Middleware HTTP, Auth, Resources embarcados
| | |-- Auth/ # PasswordHasher, SessionManager, InputValidator
| | |-- Resources/ # dashboard.html, chart.min.js (embarcados)
| | +-- LogFlowMiddleware # Roteamento de API e servico do dashboard
| |-- Domain/ # Entidades (LogEntry, AlertRule, User)
| |-- Infrastructure/ # Implementacoes concretas
| | |-- Logging/ # LogFlowProvider (ILoggerProvider)
| | |-- Notifications/ # Email, Teams, Webhook notifiers
| | |-- Pipeline/ # BoundedLogPipeline (Channel<T>)
| | +-- Storage/ # SQLite repositories
| +-- ServiceCollectionExtensions.cs # Registro DI
|
|-- tests/
| |-- BR.JCode.LogFlow.UnitTests/
| +-- BR.JCode.LogFlow.IntegrationTests/
|
|-- BR.JCode.LogFlow.SqlServer/ # Provider SQL Server
|-- BR.JCode.LogFlow.PostgreSql/ # Provider PostgreSQL
+-- BR.JCode.LogFlow.Example/ # Aplicacao de exemplo
Design Patterns Utilizados
| Pattern | Uso |
|---|---|
| Repository | ILogRepository, IAlertRuleRepository, IUserRepository, etc. |
| Strategy | IAlertNotifier (Email, Teams, Webhook) |
| Decorator | RetryNotifierDecorator (retry com backoff) |
| Observer | ILogPipeline subscriptions para SSE |
| Builder | Fluent configuration via LogFlowOptions |
| Factory | SqliteConnectionFactory |
| Background Service | LogFlowProcessor (hosted service) |
| Bounded Channel | Pipeline async com Channel<T> e drop policy |
🤝 Contribuindo
- Fork o repositorio
- Crie uma branch (
git checkout -b feature/minha-feature) - Commit suas alteracoes (
git commit -m 'feat: minha nova feature') - Push para a branch (
git push origin feature/minha-feature) - Abra um Pull Request
Convencoes
- Codigo em ingles, documentacao em portugues
- Seguir Clean Code / SOLID
- XML Summary em todos os metodos publicos/internos
- Testes unitarios e de integracao para novas funcionalidades
TreatWarningsAsErrorsativado em todos os projetos
📄 Licenca
<img src="https://img.shields.io/badge/MIT-Licen%C3%A7a-green?style=for-the-badge" alt="MIT License" />
Distribuido sob a licenca MIT. Veja LICENSE para mais detalhes.
<p align="center"> Desenvolvido por <strong>Jonathas Souza</strong> - Gateway de Integracao<br/> <strong>BR.JCode</strong> </p>
<p align="center"> <a href="https://github.com/JCodeArch/LogFlow"><img src="https://img.shields.io/badge/GitHub-JCodeArch%2FLogFlow-181717?style=for-the-badge&logo=github" alt="GitHub" /></a> <a href="https://www.nuget.org/packages/BR.JCode.LogFlow"><img src="https://img.shields.io/badge/NuGet-BR.JCode.LogFlow-004880?style=for-the-badge&logo=nuget" alt="NuGet" /></a> </p>
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. 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. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- BR.JCode.LogFlow (>= 1.0.0-preview.2)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Hosting.Abstractions (>= 8.0.0)
- Microsoft.Owin (>= 4.2.2)
- Newtonsoft.Json (>= 13.0.3)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.0.0-preview.2 | 32 | 3/10/2026 |
| 1.0.0-preview.1 | 45 | 3/3/2026 |