ASP.Net Core LogLevel not working - c#

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:
--------This Works--------
I found the example below at https://learn.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();
}

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

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);
});

If you are using another logging provider, like NLog, then the "Logging" appsettings for Microsoft will not work.
For NLog, you have to set the minimum logging level in the nlog.config:
<logger name="*" minlevel="Info" writeTo="default" />

Related

Azure AppInsight Log Information not working

In Asp.net Core version 3.1 I have tried to log LogInformation to Application Insights, but it is not logging in App Insight.
private readonly ILogger<LogService> _logger;
public LogService(IOptions<LogConfig> logConfig, ILogger<LogService> logger)
{
_logConfig = logConfig.Value;
_logger = logger;
}
_logger.LogInformation("Parameters: {Log Info}", _logConfig.IsLogEnabled);
But Logging Error is working
_logger.LogError(e, "Parameters: {HttpMethod}, {ErrorCode}", logEntry.HttpMethod, logEntry.ErrorCode);
Using package Microsoft.ApplicationInsights.AspNetCore version 2.21.0
In Startup.cs
services.AddApplicationInsightsTelemetry();
In appSettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Information"
}
},
"ApplicationInsights": {
"LogLevel": {
"Default": "Information"
},
"ConnectionString": "secret"
}
}
You are setting the AI loglevel at the incorrect level. It should be like this:
{
"Logging": {
"LogLevel": {
"Default": "Information"
},
"ApplicationInsights": {
"LogLevel": {
"Default": "Information"
}
}
},
"ApplicationInsights": {
"ConnectionString": "secret"
}
}

Is there a way to filter out the healthcheck logs of an ASP.NET Core 6 app in AzureAppService when using ApplicationInsights

I have setup an ASP.NET Core 6.0 web app that uses Azure ApplicationInsights.
Healthcheck is configured like this:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks();
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseEndpoints(endpoints =>
{
...
endpoints.MapHealthChecks("/healthz");
});
}
}
And when I deploy my app to azure app service my live-metrics are clogged with healthchecks:
I see in a blogpost that someone has written custom filters inside the app.
Is it possible to configure this in a more easy way?
EDIT: The quickest way was to target the logging with this config. Less accurate than accepted solution but required only config changes.
"Logging": {
"LogLevel": {
"Default": "Warning",
"Microsoft": "Warning"
},
//save healthcheck output in the storage account
"AzureAppServicesBlob": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Information",
"Microsoft": "Information",
}
},
//ignore it in the applicationinsights (live-metrics)
"ApplicationInsights": {
"LogLevel": {
"Default": "Information",
// healthcheck namespace
"Microsoft.AspNetCore.Hosting.Diagnostics": "Warning"
}
}
},
Yes, you can do this by using an ITelemetryInitializer
public class FilterHealthchecksTelemetryInitializer : ITelemetryInitializer
{
private readonly IHttpContextAccessor _httpContextAccessor;
public FilterHealthchecksTelemetryInitializer(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
}
public void Initialize(ITelemetry telemetry)
{
if ((_httpContextAccessor.HttpContext?.Request.Path.Value?.StartsWith("/healthz", StringComparison.OrdinalIgnoreCase)).GetValueOrDefault())
{
// We don't want to track health checks in the metrics.
if (telemetry is ISupportAdvancedSampling advancedSampling)
advancedSampling.ProactiveSamplingDecision = SamplingDecision.SampledOut;
// For the case that we cannot filter out the telemetry, we mark it as synthetic
if (string.IsNullOrWhiteSpace(telemetry.Context.Operation.SyntheticSource))
telemetry.Context.Operation.SyntheticSource = "HealthCheck";
}
}
}
Then just add an instance to your services and Application Insights will pick it up
services.AddSingleton<ITelemetryInitializer, FilterHealthchecksTelemetryInitializer>();

ILogger does not write to console using serilog

I'm trying to use serligo as my main logging utilitie but I can't seem to get it to work correctly.
In the Program.cs file, I configure the logger and also log a startup message, this message gets outputted to the console.
I also have, in one of my controllers, an ILogger<HomeController> instance that logs information when a certain action is called. These logs are not outputted to the console, and I cannot understand why.
Startup.cs
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
try
{
Log.Information("Starting up version {version}", Defaults.Version); // WORKS
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application start-up failed");
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration))
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Controller
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogInformation("Home/Index"); //Does not work
return View();
}
}
appsettings.json
"Serilog": {
"Using": [ "Serilog.Sinks.Console" ],
"MinimumLevel": {
"Default": "Verbose",
"Override": {
"Microsoft": "Warning",
"Microsoft.AspNetCore": "Warning",
"System": "Error"
}
},
"WriteTo": [
{
"Name": "Async",
"Args": {
"configure": [
{
"Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
"formatter": "Serilog.Formatting.Compact.RenderedCompactJsonFormatter, Serilog.Formatting.Compact"
}
}
]
}
}
]
},
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration))
The issue relates the above code, in this part of code, you should also configure it to write to the console.
Modify the code as below:
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration).WriteTo.Console())
Then, the output like this:

ILogger is not injected when using new DI functionality - Azure Functions

ILogger is not injected when using new DI functionality and not showing the log information in the console.
public class SampleGreeter : IGreeter
{
private readonly ILogger<SampleGreeter> logger;
public SampleGreeter(ILogger<SampleGreeter> logger)
{
this.logger = logger;
}
public string CreateGreeting(string name)
{
logger.LogInformation("Logging from greeter");
return $"Hello, {name}. I'm a sample greeter.";
}
}
Nothing is logged from greeter, while logging from function runtime works and is showing in the console.
host.json file:
{
"version": "2.0",
"logging": {
"applicationInsights": {
"fileLoggingMode": "debugOnly",
"logLevel": {
"default": "Information",
"<namespace>": "Information"
},
"samplingExcludedTypes": "Request",
"samplingSettings": {
"isEnabled": true
}
}
}
}
Microsoft documentation says:
"The host injects ILogger and ILoggerFactory services into constructors. However, by default these new logging filters are filtered out of the function logs. You need to modify the host.json file to opt-in to additional filters and categories."
Microsoft documentation and example
You've put
"logLevel": {
"default": "Information",
"<namespace>": "Information"
},
(and fileLoggingMode) within the applicationInsights level, but that's not the right one: it should be one level higher, as in the sample configuration file:
"logging": {
"fileLoggingMode": "debugOnly",
"logLevel": {
"default": "Information",
"<namespace>": "Information"
},
"applicationInsights": {
"samplingExcludedTypes": "Request",
"samplingSettings": {
"isEnabled": true
}
}
}

Error when get connection string: ArgumentNullException: Value cannot be null. Parameter name: connectionString

I am using ASP.NET Core 2.0. Below is my code.
Startup:
namespace foo
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services
.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
services.AddDbContext<fooContext>(options => options.UseSqlServer(Configuration.GetConnectionString("UserDatabase")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
appsettings.json:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
},
"ConnectionStrings": {
"UserDatabase": "Server=DESKTOP-FSES7UK;Database=xxx;User Id=sa; Password=xxxxxxx;Trusted_Connection=True;"
}
}
}
How to fix it?
As mentioned in the comment, try to move your connection string to the top (suggestion) fix is to take the key *"ConnectionStrings" *outside of logging key
appsettings.json
{
"ConnectionStrings": {
"UserDatabase": "Server=DESKTOP-FSES7UK;Database=xxx;User Id=sa; Password=xxxxxxx;Trusted_Connection=True;"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
Problem is your ConnectionStrings object has been a property of Logging object. Write your appsettings.json as follows:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
},
},
"ConnectionStrings": {
"UserDatabase": "Server=DESKTOP-FSES7UK;Database=xxx;User Id=sa; Password=xxxxxxx;Trusted_Connection=True;"
}
}

Categories