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"
}
}
}
}
Related
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"
}
}
}
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.
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": "*"
}
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"
}
}
I'm trying to configure Mvc routes using Areas.
This is the simplest version of my attempts.
Demo Controller
using System;
using Microsoft.AspNetCore.Mvc;
namespace SampleApp.Controllers
{
[Area("Demo")]
public class DemoController: Controller
{
[HttpGet("hello")]
public string Hello() => "Hello Guest";
}
}
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc(routes =>
{
routes.MapAreaRoute(
name: "demo_area",
areaName: "Demo",
template: "super/demo/{controller}/{action}",
defaults: new { controller = "Demo", action = "Hello" });
});
}
I've also implemented a Debug controller to examine the router that returns the following route definition:
{
"action": "Hello",
"controller": "Demo",
"dataTokens": null,
"defaults": null,
"name": null,
"template": "hello" // -> Get http://localhost:5000/hello
}
Found it (and very disappointed).
Reading again the routing documentation there's a clear statement: «conventional and attribute based routing cannot be mixed». In these cases the latter wins.
I was wrong using the HttpGetattribute.
Edit
I've done some work to overcame this limitation. I'm not aware of an equivalent easy solution provided by the framework.
I've implemented a simple RouteModuleAttribute and an IRouteBuilder extension method that interact to provide the requested behaviour.
The full solution, which is out of scope for this thread, is available on GitHub.