serilog / serilog-settings-configuration

A Serilog configuration provider that reads from Microsoft.Extensions.Configuration
Apache License 2.0
444 stars 129 forks source link

Serilog not getting settings from appsettings.json in Net Core API 8 #415

Closed eleazarcelis closed 3 weeks ago

eleazarcelis commented 5 months ago

Description ReadFrom.Configuration is not able to use configuration parameters from the appsettings.json file. It does not write the expected format on the console, it does not generate the expected log file.

this is my appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    },
    "Serilog": {
      "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
      "MinimumLevel": "Debug",
      "Override": {
        "Microsoft.AspNetCore": "Warning",
        "Microsoft": "Warning",
        "System": "Warning"
      },
      "Enrich": [ "FromLogContext" ],
      "WriteTo": [
        {
          "Name": "Console",
          "Args": {
            "formatter": {
              // `type` (or $type) is optional, must be specified for abstract declared parameter types
              "type": "Serilog.Templates.ExpressionTemplate, Serilog.Expressions",
              "template": "[{@t:HH:mm:ss} {@l:u3} ---- {Coalesce(SourceContext, '<none>')}] {@m}\n{@x}"
            }
          }
        },
        {
          "Name": "File",
          "Args": {
            "path": "\\logs\\log.txt"
          }
        }
      ]
    }
  }

the appsettings class:

    public class AppSettings
    {
        private static AppSettings? _instance;
        private static IConfiguration _configuration;

        public static AppSettings Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new AppSettings();
                }
                return _instance;
            }
        }

        public IConfiguration Configuration
        {
            get
            {
                return _configuration;
            }
        }

        public AppSettings()
        {
            string OS = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "Linux" : "Windows";

            _configuration = new ConfigurationBuilder()
                .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                .AddJsonFile($"appsettings.{OS}.json")
                .AddEnvironmentVariables()
                .Build();
        }

        public static void Reload()
        {
            _instance = new AppSettings();
        }
    }`

the main:

public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);

    builder.Configuration.AddConfiguration(AppSettings.Instance.Configuration);

    builder.Host.UseSerilog((context, services, configuration) => configuration
        .ReadFrom.Configuration(context.Configuration)
        .ReadFrom.Services(services)
        .Enrich.FromLogContext()
        .WriteTo.Console()
    );

    // Add services to the container.
    ConfigureServices(builder.Services);

    var app = builder.Build();

    //app.UseSerilogRequestLogging();

    MigrateDatabase(app);

    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();

    app.UseAuthentication();
    app.UseAuthorization();

    app.MapControllers();

    app.Run();

    Log.Debug("######################################################################################################");
}

Reproduction add nuget package: dotnet add package Serilog (3.1.1) dotnet add package Serilog.AspNetCore (8.0.1) dotnet add package Serilog.Sinks.Console (5.0.1) dotnet add package Serilog.Sinks.File (5.0.0)

Expected behavior See the expected format on the console and the file in the expected folder

Relevant package, tooling and runtime versions N/A

Additional context Framework: Net Core 8
Project type: API

pratitid09 commented 5 months ago

i want to take the bug and work on it

nblumhardt commented 5 months ago

Hi! This doesn't look like a Serilog bug - it's probably better to post this one to Stack Overflow and work through all of the details around your setup. At first glance it looks like your JSON config is invalid - "Serillog" should be a root element and not under "Logging". HTH!

eleazarcelis commented 5 months ago

{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" }, "Serilog": { "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ], "MinimumLevel": "Debug", "Override": { "Microsoft.AspNetCore": "Warning", "Microsoft": "Warning", "System": "Warning" }, "Enrich": [ "FromLogContext" ], "WriteTo": [ { "Name": "Console", "Args": { "formatter": { //type(or $type) is optional, must be specified for abstract declared parameter types "type": "Serilog.Templates.ExpressionTemplate, Serilog.Expressions", "template": "[{@t:HH:mm:ss} {@l:u3} ---- {Coalesce(SourceContext, '<none>')}] {@m}\n{@x}" } } }, { "Name": "File", "Args": { "path": "\\logs\\log.txt" } } ] } }

Thanks! Maybe you should consider explicitly including this information on https://github.com/serilog/serilog-settings-configuration for clueless folks.

bartelink commented 5 months ago

Maybe you should consider explicitly including this information on https://github.com/serilog/serilog-settings-configuration for clueless folks.

If you could make a PR that contains an example that would have helped you, that'd be a really great help for all concerned.

"The obvious thing to show" is never as obvious when you wrote it and/or have used it lots of times and it just worked (either because somebody else rigged it or you copied from something that had it correct).

eleazarcelis commented 5 months ago

Maybe you should consider explicitly including this information on https://github.com/serilog/serilog-settings-configuration for clueless folks.

If you could make a PR that contains an example that would have helped you, that'd be a really great help for all concerned.

"The obvious thing to show" is never as obvious when you wrote it and/or have used it lots of times and it just worked (either because somebody else rigged it or you copied from something that had it correct).

I have generated PR #416 I hope this will help.

bartelink commented 5 months ago

Thank you! (I personally have never used the package, so someone more familiar with it will be along to review and/or merge it in due course)

0xced commented 3 weeks ago

Thanks for your contribution @eleazarcelis.