i am trying to get Serilog file sink working on my ASP.Net core 2.2 application based on the the documentation. I am not able to see logs in my application. What am I missing?
Program.cs:
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Serilog;
using System;
namespace Scrubber
{
public class Program
{
private static string _environmentName;
public static void Main(string[] args)
{
try
{
var iWebHost = CreateWebHostBuilder(args).Build();
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{_environmentName}.json", optional: true, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration.GetSection("Serilog"))
.CreateLogger();
Log.Logger = logger;
Log.Information("Application starting");
iWebHost.Run();
}
catch(Exception exception)
{
Log.Error(exception.ToString());
}
finally
{
Log.CloseAndFlush();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, config) =>
{
//config.ClearProviders();
_environmentName = hostingContext.HostingEnvironment.EnvironmentName;
})
.UseStartup<Startup>();
}
}
Appsettings.development.json:
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"Serilog": {
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "log.txt",
"rollingInterval": "Day"
}
}
]
}
}
A possible reason is that the App didn't load the configuration at all.
Note you set up the configuration in the following way:
var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{_environmentName}.json", optional: true, reloadOnChange: true) .Build();
ConfigurationBuilder
optional
json file by setting optional: false
As a result, if the json file doesn't reside in the right place, it fails silently.
I suggest you could change your code as below:
// get the real path
// or by reflection
// or by injection,
var path = Directory.GetCurrentDirectory(); // assume the current directory
var configuration = new ConfigurationBuilder()
.SetBasePath(path) // set the right path
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) // make it required
.AddJsonFile($"appsettings.{_environmentName}.json", optional: true, reloadOnChange: true)
.Build();
Hope it helps.