Reputation: 3931
I am trying to configure Serilog
to read my settings from the appsettings.json
file in my ASP.NET Core 2 WebApi.
I have the following in the root of the appsetting.json
file;
"Serilog": {
"Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Async", "Serilog.Sinks.MSSqlServer" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "Async",
"Args": {
"configure": [
{
"Name": "File",
"Args": { "pathFormat": "Logs\\Serilog\\log.txt" },
"RollingInterval": "Day"
},
{
"Name": "MSSqlServer",
"Args": {
"connectionString": "myconnectionstring",
"schemaName": "Schema",
"tableName": "Logs",
"batchPostingLimit": 1000,
"period": 30
}
}
]
}
}
]
}
In my Startup.cs
I have the following;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var log = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration)
.CreateLogger();
loggerFactory.AddSerilog(log);
If I run the following then the output perfectly so I know its down to the move to appsettings;
var log = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.MSSqlServer("connectionString", "Logs", schemaName:"Schema")
.WriteTo.File("Logs\\Serilog\\log.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
And then in my Program.cs
I have;
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(config =>
config.AddJsonFile(
x =>
{
x.Path = "appsettings.json";
x.Optional = true;
x.ReloadOnChange = true;
})
.AddJsonFile(
x =>
{
x.Path = "appsettings.{currentEnv}.json";
x.Optional = true;
x.ReloadOnChange = true;
})
)
.UseStartup<Startup>()
.Build();
To note, both appsettings.json and the environment specific currently contain the same data.
I have the following versions of Serilog installed;
Serilog 2.7.1 Serilog.spNetCore 2.1.1 Serilog.Enrichers.Environment 2.1.2 Serilog.Settings.Configuration 3.0.1 Serilog.Sinks.Async 1.3.0 Serilog.Sinks.File 4.0.0 Serilog.Sinks.MSSqlServer 5.1.2
Upvotes: 3
Views: 1240
Reputation: 3076
Try this in your Program.cs file:
UseStartup<Startup>()
.UseSerilog()
.Build();
That will tell the HostBuilder to use the Serilog package.
Upvotes: 4