- appsettings.json/Development.json에 Serilog 섹션 추가 (Console/File Sink, Rolling Daily) - RequestIdMiddleware 구현 (X-Request-ID 헤더 발급/반환) - Program.cs에 Serilog 호스트 빌더 + UseSerilogRequestLogging 등록 - 환경별 로그 레벨 분리 (Development: Debug, Production: Warning)
90 lines
2.4 KiB
C#
90 lines
2.4 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Serilog;
|
|
using SPMS.API.Extensions;
|
|
using SPMS.API.Middlewares;
|
|
using SPMS.Application.Interfaces;
|
|
using SPMS.Domain.Interfaces;
|
|
using SPMS.Infrastructure;
|
|
using SPMS.Infrastructure.Auth;
|
|
using SPMS.Infrastructure.Persistence;
|
|
using SPMS.Infrastructure.Persistence.Repositories;
|
|
|
|
|
|
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
|
|
{
|
|
WebRootPath = Environment.GetEnvironmentVariable("ASPNETCORE_WEBROOT")
|
|
?? "wwwroot"
|
|
});
|
|
|
|
// ===== 1. Serilog =====
|
|
builder.Host.UseSerilog((context, config) =>
|
|
config.ReadFrom.Configuration(context.Configuration));
|
|
|
|
builder.Services.AddControllers();
|
|
builder.Services.AddOpenApi();
|
|
|
|
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
|
|
|
|
builder.Services.AddDbContext<AppDbContext>(options =>
|
|
options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));
|
|
|
|
builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
|
|
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
|
|
builder.Services.AddScoped<IJwtService, JwtService>();
|
|
|
|
// JWT 인증/인가
|
|
builder.Services.AddJwtAuthentication(builder.Configuration);
|
|
builder.Services.AddAuthorizationPolicies();
|
|
|
|
var app = builder.Build();
|
|
|
|
// ── 1. 예외 처리 (최외곽 — 이후 모든 미들웨어 예외 포착) ──
|
|
app.UseMiddleware<ExceptionMiddleware>();
|
|
|
|
// ── 3. X-Request-ID 발급/반환 (클라이언트 디버깅용) ──
|
|
app.UseMiddleware<RequestIdMiddleware>();
|
|
|
|
// ── 4. Serilog 구조적 로깅 (X-Request-ID 이후에 위치) ──
|
|
app.UseSerilogRequestLogging(options =>
|
|
{
|
|
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
|
|
{
|
|
if (httpContext.Items.TryGetValue("RequestId", out var requestId))
|
|
{
|
|
diagnosticContext.Set("RequestId", requestId);
|
|
}
|
|
};
|
|
});
|
|
|
|
// Configure the HTTP request pipeline.
|
|
if (app.Environment.IsDevelopment())
|
|
{
|
|
app.MapOpenApi();
|
|
}
|
|
var webRoot = app.Environment.WebRootPath;
|
|
Console.WriteLine($"[System] Web Root Path: {webRoot}");
|
|
|
|
if (Directory.Exists(webRoot))
|
|
{
|
|
app.UseStaticFiles();
|
|
}
|
|
else
|
|
{
|
|
Console.WriteLine("[Error] Web root folder not found!");
|
|
}
|
|
|
|
app.UseHttpsRedirection();
|
|
app.UseRouting();
|
|
|
|
// ── 10. JWT 인증 ──
|
|
app.UseAuthentication();
|
|
|
|
// ── 11. 역할 인가 ──
|
|
app.UseAuthorization();
|
|
|
|
// [엔드포인트 매핑]
|
|
app.MapControllers();
|
|
app.MapFallbackToFile("index.html");
|
|
|
|
app.Run();
|