提问人:sathoril 提问时间:12/26/2021 更新时间:3/23/2022 访问量:4120
无法在 .NET 6 项目上使用 Serilog 中间件
Can't use Serilog Middleware on .NET 6 Project
问:
我正在构建一个 .NET 6 项目,并尝试让 Serilog 正常工作。
一切似乎都正常,但是当我尝试为请求添加 SerilogMiddlware 时,我收到以下异常:Unable to resolve service for type 'Serilog.Extensions.Hosting.DiagnosticContext' while attempting to activate 'Serilog.AspNetCore.RequestLoggingMiddleware'.
当我添加我的启动文件时,我得到了我提到的异常。app.UseSerilogRequestLogging()
Configure
我找不到如何在 .NET 6 上实现 Serilog 的适当示例,仅在 .NET 5 上,而且我找不到与我有相同问题的人。
我只是不知道出了什么问题,这里有我的和文件。Program.cs
Startup.cs
程序.cs如下:
using {ProjectUsing};
using {ProjectUsing};
using Serilog;
SerilogConfiguration.ConfigureSerilog();
try
{
var builder = WebApplication.CreateBuilder(args)
.UseStartup<Startup>();
builder.Host.UseSerilog((context, services, configuration) => configuration
.WriteTo.Console()
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
.Enrich.WithEnvironmentName()
.Enrich.WithMachineName()
.WriteTo.Console(
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}"));
}
catch (Exception ex)
{
Log.Fatal(ex, "Error during initialization");
}
finally
{
Log.Information("App finished");
Log.CloseAndFlush();
}
下面的启动 .cs:
using {ProjectUsing};
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Serilog;
using Serilog.Events;
using Serilog.Configuration;
using Serilog.Events;
using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace {ProjectUsing}
{
public class Startup : IStartup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
// Add services to the container.
services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
services.AddEndpointsApiExplorer();
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Project", Version = "v1" }); });
// Other Configurations
services.ConfigureDbContext(Configuration);
services.ConfigureProjectRepositories();
}
public void Configure(WebApplication app, IWebHostEnvironment environment)
{
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Project - v1"));
}
// I get the exception I mentioned when I add the following line:
app.UseSerilogRequestLogging();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
public interface IStartup
{
IConfiguration Configuration { get; }
void Configure(WebApplication app, IWebHostEnvironment environment);
void ConfigureServices(IServiceCollection services);
}
public static class StartupExtensions
{
public static WebApplicationBuilder UseStartup<TStartup>(this WebApplicationBuilder WebAppBuilder) where TStartup: IStartup
{
var startup = Activator.CreateInstance(typeof(TStartup), WebAppBuilder.Configuration) as IStartup;
if (startup == null) throw new ArgumentException("Invalid Startup.cs");
startup.ConfigureServices(WebAppBuilder.Services);
var app = WebAppBuilder.Build();
startup.Configure(app, app.Environment);
app.Run();
return WebAppBuilder;
}
}
}
答:
2赞
Serg.ID
3/23/2022
#1
我不太确定为什么它不适用于您的特定场景,但是当您添加它时,需要使用 .这是代码中的一个案例。但是,Startup 的调用顺序可能是问题所在,因为之前会调用app.UseSerilogRequestLogging()
UseSerilog()
UseSerilogRequestLogging
UseSerilog
在 .Net 6 中,当您没有 Startup 和 Main 类时,它可以在程序 .cs 中使用,例如:
try
{
var builder = WebApplication.CreateBuilder(args);
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.CreateLogger();
builder.Host.UseSerilog(logger);
// more configuration
var app = builder.Build();
app.UseSerilogRequestLogging();
// more configs
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Unhandled exception");
}
finally
{
Log.Information("Shut down complete");
Log.CloseAndFlush();
}
评论
0赞
user1912383
11/11/2023
就我而言,解决问题的是 Log.logger = logger;然后调用 Builder。主机.UseSerilog();
评论