RetailSolutions.Shared.Logs 1.3.1449

dotnet add package RetailSolutions.Shared.Logs --version 1.3.1449
                    
NuGet\Install-Package RetailSolutions.Shared.Logs -Version 1.3.1449
                    
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="RetailSolutions.Shared.Logs" Version="1.3.1449" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="RetailSolutions.Shared.Logs" Version="1.3.1449" />
                    
Directory.Packages.props
<PackageReference Include="RetailSolutions.Shared.Logs" />
                    
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 RetailSolutions.Shared.Logs --version 1.3.1449
                    
#r "nuget: RetailSolutions.Shared.Logs, 1.3.1449"
                    
#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 RetailSolutions.Shared.Logs@1.3.1449
                    
#: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=RetailSolutions.Shared.Logs&version=1.3.1449
                    
Install as a Cake Addin
#tool nuget:?package=RetailSolutions.Shared.Logs&version=1.3.1449
                    
Install as a Cake Tool

RetailSolutions.Shared.Logs

Biblioteca .NET para abstrações de logging com suporte a Serilog, Elasticsearch e Sentry — projetada para microsserviços e APIs ASP.NET Core.

Funcionalidades

  • Configuração simplificada do Serilog com suporte a HostApplicationBuilder e WebApplicationBuilder
  • Integração com Elasticsearch via Data Streams (abordagem recomendada para logs)
  • Integração com Sentry para monitoramento e rastreamento de erros
  • Enriquecimento automático de logs (exceções, ambiente, nome da aplicação, contexto)
  • Enriquecimento de contexto HTTP: IP do cliente, Correlation ID, User-Agent
  • Resiliência embutida — a aplicação não falha se o Elasticsearch estiver indisponível
  • Log em arquivo com rotação por tamanho e retenção configurável
  • Cliente Elasticsearch para operações customizadas de indexação e consulta
  • Constantes padronizadas de log para consistência entre serviços

Instalação

.NET CLI

dotnet add package RetailSolutions.Shared.Logs

Package Manager

Install-Package RetailSolutions.Shared.Logs

PackageReference

<PackageReference Include="RetailSolutions.Shared.Logs" Version="1.0.0" />

Requisitos

  • .NET 10.0 ou superior
  • Elasticsearch 8.0+ (opcional)
  • Conta Sentry (opcional)

Configuração do Serilog

HostApplicationBuilder (Worker Services, Console Apps)

using RetailSolutions.Shared.Logs;
using RetailSolutions.Shared.Logs.Elasticsearch;
using static RetailSolutions.Shared.Logs.SerilogExtension;

var builder = Host.CreateApplicationBuilder(args);

builder.AddSerilog(builder.Configuration, new SerilogConfiguration
{
    ApplicationName = "MeuServico",
    EnrichedClientInfo = false,
    Elasticsearch = new ElasticConfiguration
    {
        Enabled = true,
        Uri = "https://elasticsearch:9200",
        User = "elastic",
        Password = "senha",
        DataStreamName = "logs",
        IndexName = "meu-servico"
    },
    Sentry = new SentryConfiguration
    {
        Enabled = true,
        Dsn = "https://dsn@sentry.io/id",
        MinimumLevel = LogEventLevel.Warning,
        Environment = "Production",
        Release = "1.0.0"
    }
});

var app = builder.Build();
await app.RunAsync();

WebApplicationBuilder (ASP.NET Core APIs)

using RetailSolutions.Shared.Logs;
using RetailSolutions.Shared.Logs.Elasticsearch;
using static RetailSolutions.Shared.Logs.SerilogExtension;

var builder = WebApplication.CreateBuilder(args);

builder.AddSerilog(builder.Configuration, new SerilogConfiguration
{
    ApplicationName = "MinhaApi",
    EnrichedClientInfo = true  // habilita IP, CorrelationId, User-Agent
});

var app = builder.Build();
app.Run();

appsettings.json

O nível mínimo de log e overrides por namespace são configurados via Serilog padrão:

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning",
        "Microsoft.AspNetCore": "Warning"
      }
    }
  }
}

Sinks Disponíveis

Console

Habilitado por padrão. Formato:

2025-01-27 14:30:00.000 +00:00 [INF] Mensagem { Properties }

Elasticsearch

Usa Data Streams, com nome gerado automaticamente no padrão:

{DataStreamName}-{IndexName}-{Environment}

Exemplo: logs-meu-servico-Production

Propriedade Padrão Descrição
Enabled false Habilita o sink
Uri URI do cluster
User Usuário (opcional)
Password Senha (opcional)
DataStreamName "log" Tipo do data stream
IndexName "microservices" Dataset (obrigatório se habilitado)

Resiliência: se o Elasticsearch estiver inacessível ou mal configurado, a aplicação continua funcionando normalmente. Erros são reportados via System.Diagnostics.Trace.

Sentry

Propriedade Padrão Descrição
Enabled false Habilita o sink
Dsn DSN do projeto (obrigatório)
MinimumLevel Warning Nível mínimo de log
Environment Ambiente (opcional)
Release Versão da aplicação (opcional)

Arquivo de Texto

new SerilogConfiguration
{
    ApplicationName = "MeuServico",
    Text = new TextConfiguration
    {
        File = true,
        Path = "logs",           // diretório
        FileName = "log.txt",    // nome do arquivo
        FileSizeLimitBytes = 10 * 1024 * 1024,  // 10 MB
        RetainedFileCountLimit = 31
    }
}
Propriedade Padrão Descrição
File false Habilita log em arquivo
Path "logs" Diretório onde os arquivos serão criados
FileName "log.txt" Nome do arquivo de log
FileSizeLimitBytes 10 MB Tamanho máximo antes de criar novo arquivo
RetainedFileCountLimit 31 Quantidade máxima de arquivos mantidos

Enriquecimento de Logs

Todos os logs incluem automaticamente:

  • ApplicationName — nome configurado em SerilogConfiguration.ApplicationName
  • EnvironmentName — valor de DOTNET_ENVIRONMENT ou ASPNETCORE_ENVIRONMENT
  • ExceptionDetail — detalhes completos de exceções via Serilog.Exceptions
  • Contexto de log (LogContext)

Quando EnrichedClientInfo = true (recomendado para APIs):

  • ClientIp — IP do cliente
  • CorrelationId — header correlation-id (gerado automaticamente se ausente)
  • User-Agent — header do cliente

Cliente Elasticsearch

Para operações diretas de indexação e consulta além do logging:

// Registro
builder.AddElasticsearchClient();

// Criação de índices na inicialização
var app = builder.Build();
await app.UseElasticsearchClient("meu-indice");
// ou múltiplos índices
await app.UseElasticsearchClient(new[] { "indice-a", "indice-b" });

Injeção de dependência

using RetailSolutions.Shared.Logs.Elasticsearch;

public class MeuServico
{
    private readonly IElastic _elastic;

    public MeuServico(IElastic elastic) => _elastic = elastic;

    public async Task SalvarAsync(string id, MeuDado dado)
    {
        await _elastic.SendDataToElasticAsync("meu-indice", id, dado);
    }

    public async Task<MeuDado> BuscarAsync(string id)
    {
        return await _elastic.GetDataFromElasticAsync<MeuDado>("meu-indice", id);
    }
}

Interface IElastic

Método Descrição
SetupElasticAsync() Cria índices padrão na inicialização
SendDataToElasticAsync<T> Indexa qualquer objeto serializado como JSON
GetDataFromElasticAsync<T> Busca e desserializa um documento por ID
SendAvailabeDataToIntegrateAsync Registra quantidade de registros pendentes
SendPedidoVendaAsync Indexa payload de pedido de venda
SendClientesAsync Indexa payload de cliente
GetPedidoVendaMaxLogAsync Busca log de pedido de venda por ID

A configuração do cliente usa a seção ElasticConfiguration do appsettings.json por padrão:

{
  "ElasticConfiguration": {
    "Enabled": true,
    "Uri": "https://elasticsearch:9200",
    "User": "elastic",
    "Password": "senha",
    "DataStreamName": "log",
    "IndexName": "microservices"
  }
}

Constantes de Log

Use LogConstants para padronizar nomes de propriedades e mensagens entre serviços:

using RetailSolutions.Shared.Logs;

_logger.LogInformation(LogConstants.LOG_SERVICE_STARTING_SERVICE, "NomeIntegracao");
_logger.LogWarning(LogConstants.LOG_WARNING_SEM_ARGUMENTOS);

// Estruturado
using (LogContext.PushProperty(LogConstants.LOG_ENDPOINT, endpoint))
{
    _logger.LogInformation(LogConstants.LOG_REQUEST);
}
Constante Valor
LOG_WARNING_SEM_ARGUMENTOS "Sem argumentos, Ignorando execução"
LOG_APPLICATION_LIFECYCLE "Application.Lifecycle"
LOG_SERVICE_STARTING_SERVICE "🚀 Iniciando integração {0}"
LOG_REQUEST "Request"
LOG_RESPONSE "Response"
LOG_ENDPOINT "Endpoint"
LogPropertyRequestPath "Request.Path"
LogAffectedRows "RegistrosAfetados"

Dependências

Pacote Versão
Serilog 4.3.0
Serilog.Sinks.Console 6.1.1
Serilog.Sinks.File 7.0.0
Elastic.Serilog.Sinks 9.0.0
Elastic.Clients.Elasticsearch 9.2.2
Serilog.Sinks.Sentry 2.4.3
Serilog.Enrichers.ClientInfo 2.8.0
Serilog.Exceptions 8.4.0
Serilog.Extensions.Hosting 10.0.0
Serilog.Settings.Configuration 10.0.0

Licenca

Copyright © Retail Solutions. Todos os direitos reservados.


Autores: Renato Campos — Retail Solutions

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  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 (1)

Showing the top 1 NuGet packages that depend on RetailSolutions.Shared.Logs:

Package Downloads
RetailSolutions.Shared.Jobs

Controle de execução de cronjobs

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.3.1449 247 7/14/2026
1.3.1441 121 7/14/2026
1.3.1394 105 7/6/2026
1.3.1378 116 7/6/2026
1.2.111 104 4/30/2026
1.2.105 125 2/13/2026
1.2.104 124 2/13/2026
1.2.98 297 2/13/2026
1.2.97 127 2/8/2026
1.2.94 474 1/27/2026
1.2.93 338 12/13/2025
1.2.92 192 12/13/2025
1.2.85 202 12/13/2025
1.2.77 176 12/13/2025