16
votes

I'm having trouble getting the logger to work like i want it to. I've set the loglevel to warning, but the console window is still bloated with info logs.

I've provided some examples below, nothing extra is configured in Startup.cs or Program.cs.

I'm happy to provide more information if needed.

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "ConnectionString"
  },
  "Logging": {
    "IncludeScopes": false, 
    "LogLevel": {
      "Default": "Warning",
      "Microsoft": "Warning"
    }
  }
}

Logging example:

public class DishRepository : IDishRepository
{
    private readonly ApplicationDbContext _context;
    private readonly ILogger<DishRepository> _logger;

    public DishRepository(ApplicationDbContext context, ILogger<DishRepository> logger)
    {
        _context = context;
        _logger = logger;
    }

    public IEnumerable<Dish> GetAll()
    {
        try
        {
            _logger.LogInformation("GetAll was called");

            return _context.Dishes
                .Include(d => d.Category)
                .Include(d => d.DishIngredients)
                .ThenInclude(di => di.Ingredient)
                .Include(d => d.PizzaType).ToList();
        }
        catch (Exception e)
        {
            _logger.LogError($"Failed to get all dishes: {e}");
            return Enumerable.Empty<Dish>();
        }

    }
}

When i run my program via VisualStudio i get this:

dotnet console

--------This Works--------

I found the example below at https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?tabs=aspnetcore2x it works, but I don't understand why this works and not the appsettings.json example above.

appsettings.json

  "Logging": {
"IncludeScopes": false,
"Debug": {
  "LogLevel": {
    "Default": "Warning"
  }
},
"Console": {
  "LogLevel": {
    "PizzeriaAngular": "Warning",
    "Microsoft": "Warning",
    "Microsoft.AspNetCore": "Warning",
    "Microsoft.EntityFrameworkCore": "Information" 
  }
},
"LogLevel": {
  "Default": "Debug"
}

}

Program.cs still looks like this:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}
2

2 Answers

32
votes

There are two config files appsettings.json and appsettings.Development.json. And system use it in development mode.

4
votes

This code work for me (NetCore 2.x) in class Startup.cs in method ConfigureServices(IServiceCollection services)

services.AddLogging(builder =>
        {
            builder.SetMinimumLevel(LogLevel.Trace);
            builder.AddFilter("Microsoft", LogLevel.Warning);
            builder.AddFilter("System", LogLevel.Error);
            builder.AddFilter("Engine", LogLevel.Warning);
        });