Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

netcore2 console app configure loglevel at appsettings

I try to add a logger to my console app. All configuration apply correctly, except Logging

Program.cs:

   private static void Main(string[] args)
    {
        var services = new ServiceCollection();
        ConfigureServices(services);

        var serviceProvider = services.BuildServiceProvider();

        serviceProvider.GetService<App>().Run();
        Console.ReadKey();
    }

    private static void ConfigureServices(ServiceCollection services)
    {

        var envName = Environment.GetEnvironmentVariable("MY_ENV") ?? DevelopmentEnvName;

        var configuration = new ConfigurationBuilder()
                            .SetBasePath(Directory.GetCurrentDirectory())
                            .AddJsonFile("appsettings.json", false)
                            .AddJsonFile($"appsettings.{envName}.json", true, true)
                            .AddEnvironmentVariables()
                            .Build();

        services.AddSingleton(configuration);
        services.AddLogging(builder =>
                            {
                                builder.AddConfiguration(configuration)
                                       .AddConsole()
                                       .AddDebug();
                            });

        ConfigureOptions(services, configuration);

        ConfigureDependencies(services);
    }

In App.Run() I try log debug and info message

 public void Run()
 {
    _logger.LogDebug("Debug");
    _logger.LogDebug(_appOptions.Env);   //print nothing

    _logger.LogInformation("Info");
    _logger.LogInformation(_appOptions.Env);  //print Info and debug env lines
 }

appsettings.json:

 {
     "Logging": {
         "IncludeScopes": false,
         "LogLevel": {
              "Default": "Information"
         }
     },
     "AppOptions": {
         "Env": "none"
     }
}

appsettings.Dev.json:

 {
     "Logging": {
         "IncludeScopes": false,
         "LogLevel": {
              "Default": "Debug"
         }
     },
     "AppOptions": {
         "Env": "debug env"
     }
}

What I need to change to control log level by json settings?

like image 697
darkhac Avatar asked Jan 26 '23 11:01

darkhac


1 Answers

The short answer is: you're missing the GetSection call in your AddConfiguration.

builder.AddConfiguration(configuration.GetSection("Logging"))...

This is my reconstruction of your program:

ConsoleApp1.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.2.4" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.Logging" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.2.0" />
  </ItemGroup>

  <ItemGroup>
    <None Update="appsettings.Dev.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
    <None Update="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>

</Project>

Program.cs

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Configuration;
using System;
using System.IO;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var services = new ServiceCollection();
            var envName = Environment.GetEnvironmentVariable("MY_ENV") ?? "Dev";

            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile($"appsettings.{envName}.json", false, true)
                                .AddEnvironmentVariables()
                                .Build();

            services.AddSingleton<IConfiguration>(configuration);
            services.AddLogging(builder =>
            {
                builder.ClearProviders();

                builder.AddConfiguration(configuration.GetSection("Logging"))
                       .AddConsole()
                       .AddDebug();
            });

            var provider = services.BuildServiceProvider();
            var config = provider.GetService<IConfiguration>();
            var appOptions = new AppOptions();

            config.GetSection("AppOptions").Bind(appOptions);

            var logger = provider.GetService<ILogger<Program>>();

            logger.LogDebug("Debug");
            logger.LogDebug(appOptions.Env);   //print nothing

            logger.LogInformation("Info");
            logger.LogInformation(appOptions.Env);  //print Info and debug env lines

            Console.ReadLine();
        }
    }

    public class AppOptions
    {
        public string Env { get; set; }
    }
}

appSettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  },
  "AppOptions": {
    "Env": "none"
  }
}

appSettings.Dev.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug"
    }
  },
  "AppOptions": {
    "Env": "debug env"
  }
}
like image 187
Hiral Desai Avatar answered Jan 29 '23 02:01

Hiral Desai