服务启动后看不到 Serilog 消息



我试着在Web App上练习Serilog。它用完后我看不到消息了。当我调试时,我成功地使用了OnGet()方法并触发了异常。但是,不会同时显示信息和错误消息。我只得到--> App is starting up ....消息,它在Program.cs中定义

我希望看到计数和错误消息作为输出。我错过了什么?它不是读appsettings.json吗?如果它没有被读取,它不应该覆盖微软的消息,但它会覆盖。

程序.cs

using Serilog;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();

WebApplication app;
try
{
Log.Logger = new LoggerConfiguration().CreateLogger();
builder.Host.UseSerilog((
(ctx, lc) => lc
.ReadFrom.Configuration(ctx.Configuration))
);

app = builder.Build();
app.UseSerilogRequestLogging();
Log.Information("--> App is starting up ....");
}
catch (Exception e)
{
Log.Fatal(e, "The app failed to start bruh!!");
throw;
}
finally
{
Log.CloseAndFlush();
}

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();

索引.cshtml.cs

using Microsoft.AspNetCore.Mvc.RazorPages;
namespace SeriLogApp.Pages;
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
_logger.LogInformation("My exercise app web app logging is here <----");
try
{
for (int i = 0; i < 100; i++)
{
if (i == 56)
{
throw new Exception("it our on purpose exception");
}
else
{
_logger.LogInformation("the value {LoopCountValue}", i);
}
}
}
catch (Exception e)
{
_logger.LogError(e, "--> I caught you man yoooo!! <<***--");
}
}
}

appsettings.json

{
"AllowedHosts": "*",
"Serilog": {
"Using": [],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{ "Name": "Console" }
]
}
}

该应用程序的csproj内容,其中包括必要的nuget包。

<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Serilog.AspNetCore" Version="5.0.0" />
<PackageReference Include="Serilog.Enrichers.Context" Version="4.2.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
<PackageReference Include="Serilog.Enrichers.Process" Version="2.0.2" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.3.0" />
</ItemGroup>
</Project>

只需删除

Log.CloseAndFlush();

线路

最新更新