日志级别
本课属于 Coddy ASP.NET Core 学习旅程的“Minimal APIs”单元。第 16 课,共 20 课。
每条日志都有一个级别。从低到高依次为: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 用于表示某些异常情况,但应用并未因此中断,例如请求不存在的菜谱。
挑战
简单请求不存在的菜谱时,会记录一条警告。
- 在
Program.cs中,为GET /api/recipes/{id:int}lambda 添加第二个参数ILogger<Program> logger。 - 在
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();
这节课包含一个小测验。开始学习即可作答,并记录你的进度。