Menu
CoddyTech

ILogger로 로깅하기

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

Console.WriteLine은 텍스트만 출력합니다. 로거는 각 줄을 수준과 범주와 함께 기록하며, 어떤 줄을 보관할지는 앱의 설정으로 결정됩니다. 엔드포인트는 매개변수로 이름을 지정해 로거를 받습니다. ASP.NET Core는 요청하는 모든 람다에 ILogger<T>와 같은 서비스를 전달합니다.

app.MapPost("/orders", (NewOrder input, ILogger<Program> logger) =>
{
    logger.LogInformation("Order of {Count} items for {Customer}", input.Count, input.Customer);
    return Results.Ok();
});

메시지는 템플릿입니다. 각 {Name}은 순서대로 다음 인수의 값으로 채워지고, 로거는 로그 도구에서 검색할 수 있도록 값을 이름이 지정된 필드로 보관합니다. Console에는 info: Program[0]이 표시된 다음, 다음 줄에 메시지가 표시됩니다. 수준, 범주(ILogger<Program>에서 가져온 Program), 이벤트 ID가 함께 표시됩니다.

challenge icon

챌린지

쉬움

앱은 추가하는 각 레시피를 기록합니다.

  1. Program.cs에서 POST /api/recipes 람다에 두 번째 매개변수 ILogger<Program> logger를 추가하세요.
  2. recipes.Add(recipe); 바로 뒤에 logger.LogInformation("Added recipe {Id}: {Name}", recipe.Id, recipe.Name);를 호출하세요.

직접 해 보세요: ‘실행’을 누르고 {"name":"Waffles","category":"breakfast","minutes":20}를 /api/recipes에 POST하세요. 콘솔에 info: Program[0]과 Added recipe 4: Waffles가 표시됩니다. {"minutes":5}를 POST하면 상태 코드가 400이고 로그가 기록되지 않습니다.

직접 해보기

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) =>
{
    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);
    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();

Minimal API의 모든 레슨