问题
I have creted my first asp.net core 3.0 application. And setup.cs file with serilog file extension like following:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
loggerFactory.AddFile("logs/ts-{Date}.txt");
....
And appsettings.json is:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
But this logs so many information while application running. But I want to save only my log calls in controller actions or anywhere else:
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
_logger.LogInformation("oops");
....
}
}
回答1:
The default template for .NET Core 3 projects also has a appsettings.Development.json
file which overrides settings in the base appsettings.json
file. It will look something like this:
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
Note that the log level is set to Debug
which is why your logs contain so many entries.
From the docs:
AddJsonFile
is automatically called twice when you initialize a new host builder withCreateDefaultBuilder
. The method is called to load configuration from:
- appsettings.json – This file is read first. The environment version of the file can override the values provided by the appsettings.json file.
- appsettings.{Environment}.json – The environment version of the file is loaded based on the IHostingEnvironment.EnvironmentName.
来源:https://stackoverflow.com/questions/58633749/why-asp-net-core-logging-everything