In my .NET Core 2.1 project I have installed Serilog
, but for some reason it will not log information events. It logs error events, though.
In my appSettings I have:
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Fatal",
"System": "Fatal"
}
},
"WriteTo": [
{
"Name": "File",
"Args": {
"restrictedToMinimumLevel": "Information",
"path": "D:\\Web\\098_VDSNet4\\Logs\\API.AdminPortal\\.txt",
"rollingInterval": "Day"
}
}
]
}
and in my Startup.cs I have:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.ReadFrom.Configuration(Configuration)
.CreateLogger();
services.AddLogging(logging =>
logging.AddSerilog(dispose: true)
);
In the code I have:
public IActionResult Post(Address address)
{
string functionName = "AddressController:Post";
try
{
logger.LogInformation($"{functionName}");
// TOOD Additional Address validation
addressRepository.Add(address);
addressRepository.Save();
return Ok(address);
}
catch(Exception ex)
{
logger.LogError(ex, $"{functionName}: There was an error creating the address");
return BadRequest();
}
}
logger.LogInformation
(and I have tried logger.LogDebug
as well, that doesn't work either) does not output anything. But logger.LogError
does log the correct error.
I have tried changing the default level to Verbose to see if that would kick it into life, but I can't seem to get anything below Error to be output to the log file.
You have to inject the ILogger<HomeController>
interface into your HomeController
constructor.
private readonly Microsoft.Extensions.Logging.ILogger _log;
public HomeController(ILogger<HomeController> logger)
{
_log = logger;
}
You have to tell asp.net core
from where to read the configuration (add this in Program.cs
):
public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.Build();
In the Program.cs add UseSerilog
:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog();
Results: