Can't use Serilog Middleware on .NET 6 Project

4.7k Views Asked by At

I'm building a .NET 6 project and trying to put Serilog to work properly on it.

Everything seems to work fine, but when I try to add SerilogMiddlware for requests I get this exception: Unable to resolve service for type 'Serilog.Extensions.Hosting.DiagnosticContext' while attempting to activate 'Serilog.AspNetCore.RequestLoggingMiddleware'.

When I add app.UseSerilogRequestLogging() on my Startup file, on Configure method I get the exception I mentioned.

I can't find a proper example of how to implement Serilog on .NET 6, just on .NET 5, and I can't find neither a person with the same problem as me.

I just don't know what is wrong, here I have my Program.cs and Startup.cs file.

Program.cs below:

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();
}

Startup.cs below:

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;
        }
    }
}
1

There are 1 best solutions below

1
On

I'm not too sure why it's not working your particular scenario, but when you add app.UseSerilogRequestLogging() it's required to use UseSerilog(). It is a case in your code. However, the order of invocation of Startup might be the problem, because UseSerilogRequestLogging will be called before UseSerilog

In .Net 6 when you don't have Startup and Main classes it can be used in program.cs like:

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();
}