L2.Common 1.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package L2.Common --version 1.0.0
                    
NuGet\Install-Package L2.Common -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="L2.Common" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="L2.Common" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="L2.Common" />
                    
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 L2.Common --version 1.0.0
                    
#r "nuget: L2.Common, 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 L2.Common@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=L2.Common&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=L2.Common&version=1.0.0
                    
Install as a Cake Tool

L2.Common

.NET License: MIT NuGet

Pacote NuGet com métodos e configurações comuns para projetos de estudos, focado em observabilidade e logging estruturado.

📋 Funcionalidades

🔍 Observabilidade

  • OpenTelemetry completo com tracing, métricas e logs
  • Configuração automática de instrumentação para ASP.NET Core
  • Suporte a OTLP (OpenTelemetry Protocol) para exportação
  • Correlação automática entre logs e traces
  • Middleware de logging estruturado para requisições HTTP

📚 Swagger/OpenAPI

  • Configuração automática do Swagger UI
  • Documentação XML integrada
  • Interface customizada com filtros e duração de requisições
  • Preparado para autenticação JWT (comentado)

🛠️ Utilitários

  • Constantes e helpers reutilizáveis
  • Interfaces bem definidas para injeção de dependência
  • Configurações padronizadas para diferentes ambientes

🚀 Instalação

dotnet add package L2.Common

📖 Como Usar

Configuração Básica

using L2.Commom.Configurators;
using L2.Commom.Configurators.Otel;
using L2.Commom.Middlewares;

var builder = WebApplication.CreateBuilder(args);

// Configuração do OpenTelemetry
var serviceName = Assembly.GetExecutingAssembly().GetName().Name!;
var serviceVersion = Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "1.0.0";
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";
var serviceInstanceId = Environment.MachineName;

builder.Services
    .AddOtelConfigurator(builder.Configuration, serviceName, serviceVersion, environment, serviceInstanceId, clearLoggingProviders: true)
    .UseOtelBuilder()
    .WithLogging();

// Configuração do Swagger
builder.Services.AddCustomSwagger();

builder.Services.AddControllers();

var app = builder.Build();

// Middleware de logging
app.UseMiddleware<LoggingMiddleware>();

// Swagger apenas em desenvolvimento
if (app.Environment.IsDevelopment())
    app.UseCustomSwagger();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

Configuração de Ambiente

Adicione as seguintes configurações no appsettings.json:

{
  "Observability": {
    "Otlp": {
      "Endpoint": "http://otel-collector:4317"
    }
  }
}

Ou defina a variável de ambiente:

export OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317

🏗️ Estrutura do Projeto

L2.Common.Package/
├── Configurators/
│   ├── Otel/
│   │   ├── OpenTelemetryConfigurator.cs
│   │   ├── OtelBuilder.cs
│   │   ├── OtelConfigurator.cs
│   │   └── OtelConfiguratorExtensions.cs
│   └── SwaggerConfigurator.cs
├── Handlers/
│   └── TelemetryHandler.cs
├── Helpers/
│   └── Constants.cs
├── Interfaces/
│   ├── Configurators/Otel/
│   ├── Handlers/
│   └── IRequestLogger.cs
├── Logging/
│   └── RequestLogger.cs
└── Middlewares/
    └── LoggingMiddleware.cs

🔧 Configurações Avançadas

OpenTelemetry Customizado

// Configuração apenas de tracing
builder.Services.AddOtelConfigurator(config, serviceName, serviceVersion, environment, serviceInstanceId)
    .ConfigureTracing();

// Configuração apenas de métricas
builder.Services.AddOtelConfigurator(config, serviceName, serviceVersion, environment, serviceInstanceId)
    .ConfigureMetrics();

// Configuração completa com opções customizadas
builder.Services.AddOtelConfigurator(config, serviceName, serviceVersion, environment, serviceInstanceId)
    .ConfigureCompleteTelemetry(enableTracing: true, enableMetrics: true);

Atributos Customizados

var customAttributes = new Dictionary<string, object>
{
    ["team"] = "Meu Time",
    ["application.layer"] = "API",
    ["timezone"] = "America/Sao_Paulo"
};

builder.Services.AddOtelConfigurator(
    config, 
    serviceName, 
    serviceVersion, 
    environment, 
    serviceInstanceId,
    customAttributes: customAttributes);

📊 Logs Estruturados

O pacote gera logs estruturados automaticamente com as seguintes informações:

{
  "trace_id": "abc123...",
  "span_id": "def456...",
  "method": "GET",
  "path": "/api/weather",
  "status_code": 200,
  "duration_ms": 150,
  "user": "anonymous",
  "client_ip": "192.168.1.1"
}

🧪 Projeto de Teste

O repositório inclui um projeto de teste (L2.Common.ApiTest) que demonstra como usar o pacote:

cd L2.Common.ApiTest
dotnet run

Acesse o Swagger em: https://localhost:7000/swagger

📦 Dependências

  • .NET 9.0
  • OpenTelemetry.Exporter.Console (1.12.0)
  • OpenTelemetry.Exporter.OpenTelemetryProtocol (1.12.0)
  • OpenTelemetry.Extensions.Hosting (1.12.0)
  • OpenTelemetry.Instrumentation.AspNetCore (1.12.0)
  • OpenTelemetry.Instrumentation.Http (1.12.0)
  • Swashbuckle.AspNetCore (9.0.4)

🤝 Contribuição

  1. Faça um fork do projeto
  2. Crie uma branch para sua feature (git checkout -b feature/AmazingFeature)
  3. Commit suas mudanças (git commit -m 'Add some AmazingFeature')
  4. Push para a branch (git push origin feature/AmazingFeature)
  5. Abra um Pull Request

📄 Licença

Este projeto está licenciado sob a Licença MIT - veja o arquivo LICENSE para detalhes.

👨‍💻 Autor

Danielle Oliveira

🆕 Changelog

v1.0.0

  • Configuração inicial do OpenTelemetry
  • Middleware de logging estruturado
  • Configuração do Swagger
  • Suporte a tracing, métricas e logs
  • Correlação automática entre logs e traces
Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  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

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.2 6,547 9/14/2025
1.0.1 6,540 9/14/2025
1.0.0 6,533 9/14/2025