Home > Software engineering >  How to register serilog in startup.cs file in .NET 6
How to register serilog in startup.cs file in .NET 6

Time:09-30

I am upgrading project from .NET 5 to .NET 6. In NET5 I have register serilog like below

public static IWebHostBuilder CreateWebHostBuilder(string[] args, Type startupType) =>
                  WebHost.CreateDefaultBuilder(args)
                 .ConfigureAppConfiguration((builderContext, config) =>
                   {
                     config.AddJsonFile("appsettings.local.json", optional: true);
                    })
                    .UseSerilog() // set Serilog as the logging provider
                    .UseStartup(startupType);

In .NET 6 I am getting error that UseSerilog needs to be used at IHostBuilder. Most of examples to register UseSerilog is in program.cs file. I need to register this in Startup.cs file only. Program.cs file is not there in project.

CodePudding user response:

In .NET 6, there is only one Program.cs file by default, and Startup.cs is cancelled.

If you want to keep using the Startup.cs file and configure serilog in it, you can refer to my test code below:

Startup.cs:

public class Startup
    {
        public IConfiguration configRoot{ get; }
        public Startup(IConfiguration configuration)
        {
            configRoot = configuration;
        }
        public void ConfigureServices(IServiceCollection services, IWebHostEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(builder.Build())
                .WriteTo.Console()
                .CreateLogger();
            Log.Information("Starting up");

            services.AddRazorPages();
            services.AddControllersWithViews();
            
        }
        public void Configure(WebApplication app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {

            loggerFactory.AddSerilog();
            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.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
            app.Run();
        }
    }

Program.cs:

var builder = WebApplication.CreateBuilder(args);
var startup = new Startup(builder.Configuration);
startup.ConfigureServices(builder.Services,builder.Environment); // calling ConfigureServices method
var app = builder.Build();
startup.Configure(app, builder.Environment, app.Services.GetService<ILoggerFactory>()); // calling Configure method

Don't forget to install the corresponding NuGet package(Serilog.AspNetCore, Serilog.Extensions.Hosting, Serilog.Sinks.Seq): enter image description here

Test Result:

enter image description here

  • Related