Menu
CoddyTech

로그 수준

Coddy ASP.NET Core 여정의 Minimal API 섹션에 포함된 레슨. 20개 중 16번째.

각 로그 줄에는 수준이 있습니다. 낮은 수준부터 높은 수준 순으로 Trace, Debug, Information, Warning, Error, Critical이며, 각각 LogTrace부터 LogCritical까지의 이름으로 작성합니다. 설정은 각 범주에서 유지할 최저 수준을 지정합니다. 새 ASP.NET Core 프로젝트의 appsettings.json에는 다음 내용이 있습니다.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  }
}

따라서 LogDebug 줄은 무시되고, ASP.NET Core 자체의 Information 수준 로그도 무시되는 반면 경고는 유지됩니다. 프로젝트에 appsettings.json이 없어도 ‘실행’은 동일한 수준을 적용합니다. Warning은 앱을 중단시키지는 않았지만 특이한 상황에 사용합니다. 예를 들어 존재하지 않는 레시피를 요청한 경우가 이에 해당합니다.

challenge icon

챌린지

쉬움

존재하지 않는 레시피에 대한 요청은 경고로 기록됩니다.

  1. Program.cs에서 GET /api/recipes/{id:int} 람다에 두 번째 매개변수 ILogger<Program> logger를 추가하세요.
  2. if (recipe is null) 안에서 return 앞에 logger.LogWarning("Recipe {Id} was not found", id);를 호출하세요. 이제 if에서 두 개의 문을 실행하므로 중괄호를 추가하세요.

시험해 보세요: ‘실행’을 누르세요. 첫 번째 요청인 GET /api/recipes/99는 이전처럼 404를 반환하고, 콘솔에는 warn: Program[0]과 Recipe 99 was not found가 표시됩니다. GET /api/recipes/2를 보내세요. 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) =>
{
    var recipe = recipes.FirstOrDefault(r => r.Id == id);
    if (recipe is null)
        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();
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Minimal API의 모든 레슨