Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
eleazarcelis opened this issue Mar 19, 2024 · 7 comments
Closed
Labels

Comments

@eleazarcelis
Copy link
Contributor

eleazarcelis commented Mar 19, 2024

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

@eleazarcelis eleazarcelis changed the title Serilog doesn't get settings from appsettings.json on net core api 8 Serilog not getting settings from appsettings.json in Net Core API 8 Mar 19, 2024
@pratitid09
Copy link

i want to take the bug and work on it

@nblumhardt
Copy link
Member

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!

@nblumhardt nblumhardt added question and removed bug labels Mar 19, 2024
@eleazarcelis
Copy link
Contributor Author

{ "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
Copy link
Member

bartelink commented Mar 20, 2024

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
Copy link
Contributor Author

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
Copy link
Member

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
Copy link
Member

0xced commented Aug 6, 2024

Thanks for your contribution @eleazarcelis.

@0xced 0xced closed this as completed Aug 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

5 participants