Skip to content

Commit 4fafb42

Browse files
committed
📡feat: add structured logging with Serilog & Seq observability stack
- Introduced structured logging using Serilog with centralized ingestion via Seq for improved observability and log analysis. - Added a dedicated Seq container to the Docker environment and configured the API to ship logs over HTTP. - Enabled request-level logging with Serilog middleware and reduced log noise by filtering Microsoft and System namespaces, while preserving EF Core SQL logs in Development.
1 parent 7ccefa1 commit 4fafb42

5 files changed

Lines changed: 72 additions & 12 deletions

File tree

EventFlow.Presentation/Config/AppConfiguration.cs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,17 @@ namespace EventFlow.Presentation.Config;
1717

1818
public static class AppConfiguration
1919
{
20-
public static IServiceCollection AddDbContextConfig(this IServiceCollection services, IConfiguration configuration)
20+
public static IServiceCollection AddDbContextConfig(this IServiceCollection services, IConfiguration configuration, bool isDevelopment)
2121
{
2222
var ConnectionString = configuration.GetConnectionString("DevConnectionString");
2323

2424
services.AddDbContext<EventFlowContext>(options =>
2525
{
26-
options.UseSqlServer(ConnectionString);
27-
options.EnableSensitiveDataLogging(true);
26+
if (isDevelopment)
27+
{
28+
options.EnableSensitiveDataLogging(true);
29+
options.EnableDetailedErrors(true);
30+
}
2831
});
2932

3033
return services;

EventFlow.Presentation/EventFlow.Presentation.csproj

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@
2626
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
2727
</PackageReference>
2828
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
29+
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
30+
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
31+
<PackageReference Include="Serilog.Sinks.Seq" Version="9.0.0" />
2932
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
3033
</ItemGroup>
3134

EventFlow.Presentation/Program.cs

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
11
using EventFlow.Presentation.Config;
22
using EventFlow.Infrastructure.Data;
33
using Microsoft.IdentityModel.Tokens;
4+
using Serilog;
45

56
var builder = WebApplication.CreateBuilder(args);
67

8+
builder.Host.UseSerilog((context, configuration) =>
9+
configuration.ReadFrom.Configuration(context.Configuration));
10+
711
AppConfiguration.ConfigureMvc(builder);
812

913
builder.Services.ConfigureSwagger();
1014
builder.Services.AddEndpointsApiExplorer();
1115
builder.Services.AddSwaggerGen();
12-
builder.Services.AddDbContextConfig(builder.Configuration);
16+
builder.Services.AddDbContextConfig(builder.Configuration, builder.Environment.IsDevelopment());
1317
builder.Services.AddDependencyInjectionConfig();
1418

1519
builder.Services
@@ -45,11 +49,12 @@
4549
}
4650
catch (Exception ex)
4751
{
48-
var logger = services.GetRequiredService<ILogger<Program>>();
49-
logger.LogError(ex, "Ocorreu um erro ao aplicar as migrações automáticas.");
52+
Log.Fatal(ex, "Ocorreu um erro ao aplicar as migrações automáticas.");
5053
}
5154
}
5255

56+
app.UseSerilogRequestLogging();
57+
5358
if (app.Environment.IsDevelopment())
5459
{
5560
app.UseSwagger();
@@ -61,4 +66,17 @@
6166
app.UseAuthorization();
6267

6368
app.MapControllers();
64-
app.Run();
69+
70+
try
71+
{
72+
Log.Information("Iniciando Web API...");
73+
app.Run();
74+
}
75+
catch (Exception ex)
76+
{
77+
Log.Fatal(ex, "A API caiu inesperadamente.");
78+
}
79+
finally
80+
{
81+
Log.CloseAndFlush();
82+
}

EventFlow.Presentation/appsettings.json

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,28 @@
11
{
2-
"Logging": {
3-
"LogLevel": {
2+
"Serilog": {
3+
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.Seq" ],
4+
"MinimumLevel": {
45
"Default": "Information",
5-
"Microsoft.AspNetCore": "Warning"
6-
}
6+
"Override": {
7+
"Microsoft": "Warning",
8+
"System": "Warning",
9+
"Microsoft.Hosting.Lifetime": "Information"
10+
}
11+
},
12+
"WriteTo": [
13+
{ "Name": "Console" },
14+
{
15+
"Name": "Seq",
16+
"Args": {
17+
"serverUrl": "http://localhost:5341"
18+
}
19+
}
20+
],
21+
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
722
},
823
"AllowedHosts": "*",
924
"ConnectionStrings": {
10-
"ConnectionString": "Server=INSIRA AQUI O IP; Database = NOME DO SEU BANCO DE DADOS; User Id = SEU USUARIO; Password = SUA SENHA;"
25+
"DevConnectionString": "Server=INSIRA AQUI O IP; Database = NOME DO SEU BANCO DE DADOS; User Id = SEU USUARIO; Password = SUA SENHA;"
1126
},
1227

1328
"Jwt": {

docker-compose.yml

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,18 @@ services:
1313
- ASPNETCORE_ENVIRONMENT=Development
1414
- ASPNETCORE_HTTP_PORTS=8079
1515
- ConnectionStrings__DevConnectionString=Server=eventflow-db;Database=EventFlow;User Id=sa;Password=MyStrongPassword123!;TrustServerCertificate=True;
16+
- Jwt__Issuer=EventFlowApi
17+
- Jwt__Audience=EventFlowClient
18+
- Jwt__Key=UmaChaveMuitoSecretaEMuitoLongaParaDev123!
19+
- Serilog__WriteTo__1__Args__serverUrl=http://eventflow-seq:5341
20+
- ASPNETCORE_DataProtection__KeyManagement__XmlRepository__Directory=/root/.aspnet/DataProtection-Keys
1621
depends_on:
1722
eventflow-db:
1823
condition: service_healthy
24+
eventflow-seq:
25+
condition: service_started
26+
volumes:
27+
- eventflow_keys:/root/.aspnet/DataProtection-Keys
1928
networks:
2029
- eventflow-network
2130

@@ -38,8 +47,20 @@ services:
3847
networks:
3948
- eventflow-network
4049

50+
eventflow-seq:
51+
image: datalust/seq:latest
52+
container_name: eventflow-seq
53+
environment:
54+
- ACCEPT_EULA=Y
55+
- SEQ_FIRSTRUN_ADMINPASSWORD=MyStrongPassword123!
56+
ports:
57+
- "5341:80"
58+
networks:
59+
- eventflow-network
60+
4161
volumes:
4262
eventflow_sql_data:
63+
eventflow_keys:
4364

4465
networks:
4566
eventflow-network:

0 commit comments

Comments
 (0)