dotnet core logging showing info result always - asp.net-core

I am learning .net core logging. I have read some blogs and docs also.
I am wondering why it's showing always "Microsoft.Hosting.Lifetime" Information logs every time with following settings.
{
"Logging": {
"LogLevel": {
"Default": "Error",
"Microsoft": "Error",
"Microsoft.Hosting.Lifetime": "Error",
"DemoWeb.Controllers.HomeController": "Error"
}
},
"AllowedHosts": "*"
}
To double check(If my appsettings.json is working) I added this in ConfigureService.
public void ConfigureServices(IServiceCollection services)
{
services.AddLogging(config =>
{
// clear out default configuration
config.ClearProviders();
config.AddConfiguration(Configuration.GetSection("Logging"));
config.AddDebug();
config.AddEventSourceLogger();
config.AddConsole();
});
services.AddControllersWithViews();
}
It's working as expected for my own added "HomeController" Class.
I just want to remove "Microsoft.Hosting.Lifetime" from console logs.
Thanks in advance

Firstly, as #KirkLarkin mentioned, in development, appsettings.Development.json configuration would overwrite values found in appsettings.json.
For more information, you can check : https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#appsettingsjson
want to remove "Microsoft.Hosting.Lifetime" from console logs
In your project, multiple logging providers can be enabled. If you just want to turn off Information level logs about "Microsoft.Hosting.Lifetime" from ConsoleLogger, you can try to apply log filter rule(s) as below.
services.AddLogging(config =>
{
// clear out default configuration
config.ClearProviders();
config.AddConfiguration(Configuration.GetSection("Logging"));
//add log filter for ConsoleLoggerProvider
config.AddFilter<ConsoleLoggerProvider>("Microsoft.Hosting.Lifetime", LogLevel.Error);
config.AddDebug();
config.AddEventSourceLogger();
config.AddConsole();
});
And you can achieve same by configuring logging for that specific provider.
"Console": {
"IncludeScopes": true,
"LogLevel": {
"Microsoft.Hosting.Lifetime": "Error"
}
}

Related

Prevent DefaultAntiforgery from logging errors

Is there a way to stop DefaultAntiforgery from logging errors? I see it takes an ILoggerFactory as parameter, which is a public type, but I don't know how to set it up since DefaultAntiforgery is internal.
I don't think this is a DI issue, but rather a configuration issue. What you want should be possible by configuring logging
Try something like this in your appsettings.json:
{
"Logging": {
// for all logging providers
"LogLevel": {
"Microsoft.AspNetCore.Antiforgery": "None"
},
// or just for the EventLog provider
"EventLog": {
"LogLevel": {
"Microsoft.AspNetCore.Antiforgery": "None"
}
}
}
}

Logging LogLevel-Information not showing in Windows event log [duplicate]

This question already has answers here:
How to write logs to EventLog by ILogger<T> in Asp.net Core?
(3 answers)
Closed 12 months ago.
I ran into some problems with logging **Information** Logs to Windows event log.
Starting from a blank ASP.NET Core-Web-API .Net 5
I edited the following to Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddEventLog(eventLogSettings =>
{
eventLogSettings.SourceName = "MyTestLog";
});
});
webBuilder.UseStartup<Startup>();
});
and wrote some sample logs into a Controler
public IEnumerable<WeatherForecast> Get()
{
_logger.LogCritical("Critical Log");
_logger.LogError("Error Log");
_logger.LogWarning("Warning Log");
_logger.LogInformation("Info Log");
_logger.LogDebug("Debug Log");
_logger.LogTrace("Trace Log");
...
}
If I Run it, it shows logs for Critical - Error - Warning - Information in Console. Matching what is configured in AppSettings.
appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
In Windows event log it only shows Critical, Error and Warning -Logs, not caring for my appsettings whatsoever.
I'm sure this is an easy configuration problem, but i don't find any documentation for this.
How do I get Logs with Loglevel-Information in Windows event log ?
According to this article, you could find the ASP.NET Core provide the event logging feature. Unlike the other providers, the EventLog provider does not inherit the default non-provider settings.
If EventLog log settings aren't specified, they default to LogLevel.Warning.
To log events lower than LogLevel.Warning, explicitly set the log level. The following example sets the Event Log default log level to LogLevel.Information:
"Logging": {
"EventLog": {
"LogLevel": {
"Default": "Information"
}
}
}

Serilog doesn't log to file, only to console

I'm currently working on a mono project and want to use Microsoft.Logging + Serilog there, but I stumble across the following problem:
When I configure Serilog by hand, it logs in both console and the file (if I have configured both parameters). But when I use a configuration file, Serilog always ignores logging to the file.
The configuration file is found and the parameters are read from there, because if I add "Console" there, Serilog logs into the console.
With these settings, Serilog should, as I understand it, log into the console as well as into the file. I'm expecting this log file in "folder with appsettings.json"/logs. But it only logs into the console. And when I delete "Console", it doesn't log anywhere. I don't understand why this is so I am posting a few sections of code that are fundamental. If I have not provided enough information, please write to me in comments under the question.
appsettings.json:
{
"Serilog": {
"Using": [
"Serilog.Sinks.Console"
],
"MinimumLevel": "Debug",
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithProcessId",
"WithThreadId"
],
"WriteTo": [
{
"Name": "File",
"Args": {
"Path": "logs/GUIDemo.log",
"FileSizeLimitBytes": "400000",
"RollingInterval": "Day",
"RetainedFileCountLimit": "15",
"OutputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] {Message:lj} {NewLine}{Exception}",
"shared": true
}
},
"Console"
]
}
}
Here is how I configure Serilog in one class, which methods are executed shortly after the application start:
private IContainer container;
private ILogger<Bootstrapper> logger;
...
public void OnStartup()
{
this.Configuration = this.ConfigureConfiguration();
var builder = new ContainerBuilder();
builder.RegisterModule<AutofacModule>();
this.container = builder.Build();
this.AddLogger();
this.logger = this.container.Resolve<ILogger<Bootstrapper>>();
this.LogApplicationStart();
}
And finally methods AddLogger(), LogApplicationStart() and LogApplicationStart():
private void AddLogger()
{
var loggerFactory = this.container.Resolve<ILoggerFactory>();
loggerFactory.AddSerilog();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(this.Configuration)
.CreateLogger();
}
private IConfigurationRoot ConfigureConfiguration()
{
return new ConfigurationBuilder().SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false, true)
.Build();
}
private void LogApplicationStart()
{
this.logger.LogInformation("App is started");
}
After all of this, the output in the console is (yes, it is Godot):
Mono: Log file is:
'C:\Users\Albert\AppData\Roaming/Godot/mono/mono_logs/2021_01_27 12.46.37(105008).txt'
[12:46:38 INF] App is started
The Mono log file has nothing to do with my log file. I also tried to add Log.CloseAndFlush() at the the end of LogApplicationStart() which is currently the only method in the app, but it didn't help me as well.
Of course, I know there are many similar question here, but I could not find a solution for my problem.

Controller name in URL in asp.net core?

When using the asp-controller tag helper (https://learn.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-3.1#the-form-tag-helper), it should be possible to specify the controller you want to run like this:
<form asp-controller="Demo" asp-action="Register" method="post">
Obviously, the controller here is Demo. It seems this is being transmitted from the web browser to the back end using the URL: https://localhost:44311/?action=onPost&controller=TodoItem
But this doesn't work in my case, the controller that runs is not the one in the URL, but the one connected to the page where the form is. How can I debug this, how can I see where things are going wrong? And what is the solution, is there some service to be loaded that enables this behavior?
It seems this is being transmitted from the web browser to the back end using the URL: https://localhost:44311/?action=onPost&controller=TodoItem
To fix the above issue, you can try to register services used for MVC controllers and add endpoints for controller actions, like below.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
//other configuration code here
//...
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
And make sure your razor project contains controller class(es) that inherit from Microsoft.AspNetCore.Mvc.Controller, like below.
public class DemoController : Controller
{
//...
Folder structure of my project
Test Result
I figured it out - the tag helper asp-controller does nothing when using Razor Pages, instead asp-page should be used, as described here: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-3.1
To fix this, the docs were helpful, and like #Fei Han commented, trace logging for the routing middleware. So a default appsettings.json will then look like this:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.AspNetCore.Routing": "Trace"
}
},
"AllowedHosts": "*"
}

Load asset file at Startup failed, file does not exists

I need to load some asset data to my middleware, but it seems like it can't load the file.
Here's the folder structure:
As you can see, it's already set to "Copy if newer". And the file does get copied over to the bin folder:
Here's the code at ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
var assetFile = Configuration["Assets/Files"];
var testExist = File.Exists(assetFile); // This will be false
//services.AddAsset();
}
Here's the appsettings.json:
{
"Assets": {
"Files": "Assets/something.zip"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
As of now, my only guess is there is file size limit? The .zip file is 165MB large. Just my wild guess, else I don't know why it couldn't find my file.
My guess is that the config setting ins't read properly, that's why it cannot locate the file.
Try replacing this line:
var assetFile = Configuration["Assets/Files"];
with this one:
var assetFile = Configuration["Assets:Files"];
Notice that I used colons to navigate in the appsettings.json keys, instead of a forward slash.