모든 요청 로깅하기
Coddy ASP.NET Core 여정의 Minimal API 섹션에 포함된 레슨. 20개 중 17번째.
미들웨어는 앱이 응답하는 내용을 살펴볼 수 있습니다. app.Logger는 엔드포인트 외부의 코드를 위한 로거로, 앱에 이미 있습니다. 이 미들웨어는 요청한 항목을 찾지 못한 경우 경고를 남깁니다:
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404)
app.Logger.LogWarning("Nothing at {Path}", context.Request.Path);
});await next() 뒤에 돌아오는 과정에서 상태를 읽습니다. 엔드포인트나 뒤에 있는 미들웨어가 상태를 설정한 뒤입니다. next() 전에는 상태가 여전히 200입니다. 미들웨어가 어디에 놓이는지도 중요합니다. 먼저 추가된 미들웨어는 나중에 추가된 미들웨어가 일찍 종료하는 요청을 포함해 모든 요청을 처리하며, 나가는 과정에서는 가장 마지막에 실행됩니다.
챌린지
쉬움Console에는 요청마다 한 줄씩 표시됩니다. 예: GET /api/recipes/2 -> 200.
Program.cs에서var app = builder.Build();바로 다음이자X-Api-Version미들웨어 위에 미들웨어를 추가하세요.- 먼저
await next();를 호출한 다음app.Logger.LogInformation("{Method} {Path} -> {Status}", context.Request.Method, context.Request.Path, context.Response.StatusCode);를 호출합니다.
직접 해보기: ‘실행’을 누르세요. 첫 번째 요청은 GET /recipes/2이고, Console에는 GET /recipes/2 -> 301이 표시됩니다. GET /api/recipes/99를 보내세요. 지난 수업의 경고가 표시된 다음 GET /api/recipes/99 -> 404가 표시됩니다. GET /index.html을 보내세요. GET /index.html -> 200이 표시됩니다.
직접 해보기
using Microsoft.AspNetCore.Http.HttpResults;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Use(async (context, next) =>
{
context.Response.Headers["X-Api-Version"] = "1";
await next();
});
app.Use(async (context, next) =>
{
if (context.Request.Path.StartsWithSegments("/recipes"))
{
context.Response.Redirect("/api" + context.Request.Path + context.Request.QueryString, permanent: true);
return;
}
await next();
});
app.UseStaticFiles();
var recipes = new List<Recipe>
{
new(1, "Tomato Soup", "soup", 25),
new(2, "Pancakes", "breakfast", 15),
new(3, "Lentil Soup", "soup", 40),
};
var nextId = 4;
var favoriteIds = new List<int>();
app.MapGet("/", () => "Recipe API is running");
app.MapGet("/api/recipes", (string? category) =>
recipes.Where(r => category is null || r.Category == category));
app.MapGet("/api/recipes/{id:int}", (int id, ILogger<Program> logger) =>
{
var recipe = recipes.FirstOrDefault(r => r.Id == id);
if (recipe is null)
{
logger.LogWarning("Recipe {Id} was not found", id);
return Results.NotFound(new { error = $"Recipe {id} not found" });
}
return Results.Ok(recipe);
});
app.MapPost("/api/recipes", (NewRecipe input, ILogger<Program> logger) =>
{
if (string.IsNullOrWhiteSpace(input.Name))
return Results.BadRequest(new { error = "Name is required" });
if (input.Minutes <= 0)
return Results.BadRequest(new { error = "Minutes must be more than 0" });
var recipe = new Recipe(nextId++, input.Name, input.Category, input.Minutes);
recipes.Add(recipe);
logger.LogInformation("Added recipe {Id}: {Name}", recipe.Id, recipe.Name);
return Results.Created($"/api/recipes/{recipe.Id}", recipe);
});
app.MapPut("/api/recipes/{id:int}", (int id, NewRecipe input) =>
{
var index = recipes.FindIndex(r => r.Id == id);
if (index == -1)
return Results.NotFound(new { error = $"Recipe {id} not found" });
var recipe = new Recipe(id, input.Name, input.Category, input.Minutes);
recipes[index] = recipe;
return Results.Ok(recipe);
});
app.MapDelete("/api/recipes/{id:int}", Results<NoContent, NotFound> (int id) =>
{
var removed = recipes.RemoveAll(r => r.Id == id);
return removed > 0 ? TypedResults.NoContent() : TypedResults.NotFound();
});
var favorites = app.MapGroup("/api/favorites");
favorites.MapGet("/", () => recipes.Where(r => favoriteIds.Contains(r.Id)));
favorites.MapPost("/{id:int}", (int id) =>
{
if (!recipes.Any(r => r.Id == id))
return Results.NotFound(new { error = $"Recipe {id} not found" });
if (!favoriteIds.Contains(id))
favoriteIds.Add(id);
return Results.NoContent();
});
favorites.MapDelete("/{id:int}", (int id) =>
{
favoriteIds.Remove(id);
return Results.NoContent();
});
app.Run();