Environment-specific appsettings not loading its data - .net-core

When I attempt to use custom appsettings.{environment}.json file, even though the ASPNETCORE_ENVIRONMENT environment var is correctly set to "Local" and the appsettings.Local.json file is referenced in the config sources, no data is read from it, only from appsettings.json
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
// Configure the app here.
var env = context.HostingEnvironment;
//var environmentName =
config.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
})
.UseStartup<Startup>();
Showing values from appsettings.json
Showing config values from appsettings.Local.json (empty)
------ appsettings.json ----------------------
{
"AllowedHosts": "*",
"AppSettings": {
"MailServer": "mail.somewhare.com",
"SupportContact": "somebody#somewhare.com",
"EmailEnabled": true
},
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
------ appsettings.Local.json ---------------
{
"ConnectionStrings": {
"Dbconn1": "string 1 here",
"DbConn2": "string 1 here"
},
"AllowedHosts": "*",
"AppSettings": {
"CustomerBoxRoot": "\\\\test1\\d$\\BoxFiles",
"AnotherAppSetting": 20,
"PurgeSwitch": -14
},
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}

Related

How to use Logging level parameter from appsettings.json for Serilog?

When i am trying to use Logging inside appsettings.json for config Serilog, it is ingore my LovLevel option.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Warning"
},
"FilePath": "Loggs//log.log"
}
}
I can only fix it with adding MinimumLevel option:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Warning"
},
"MinimumLevel": {
"Default": "Debug"
},
"FilePath": "Loggs//log.log"
}
}
Can i setup my minlevel of logs without adding "MinimumLevel" option and use "LowLevel" instead?
You need to set Default as your MinimumLevel.
E.g.
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Warning"
},
"FilePath": "Loggs//log.log"
}
}

How to run GELF Extension logger?

I run the sample for NET Core:
[https://github.com/mattwcole/gelf-extensions-logging/blob/dev/samples/Gelf.Extensions.Logging.Samples.NetCore2/Program.cs][1]
Then I have ran Docker
https://docs.graylog.org/en/4.0/pages/installation/docker.html?highlight=docker
Then I little bit corrected appsettings.json file:
{
"Logging": {
"Console": {
"LogLevel": {
"Default": "Debug"
}
},
"GELF": {
"Host": "127.0.0.1",
"Port": 12201,
"LogSource": "console-app-1",
"LogLevel": {
"Default": "Debug",
"Microsoft": "Debug",
"Gelf.Extensions.Logging.Samples.NetCore2": "Debug",
"Gelf.Extensions.Logging.Samples.NetCore2.Program": "Debug"
},
"LogLevel2": {
"Microsoft.AspNetCore.Mvc.Razor": "Error",
"Default": "Trace"
},
"AdditionalFields": {
"project_name": "my-project"
}
}
}
}
Run the application, it works but when I go to browser
http://localhost:9000/search?q=&rangetype=relative&relative=1800
I do not see any records.
What I do wrong?
Need to check the Docker GrayLog Configuration: especially GELF Input local and global.

Serilog and .NET Core Web API log file isn't created

I'm just starting with Serilog.
Despite all the code samples/tut's, I've found online I just can't get it to output to file (the file isn't even created). My app is a Web API (.NET Core 3.1), I'm referencing
Serilog.AspNetCore(3.4.0)
Serilog.Settings.Configurations (3.1.0)
Serilog.Sinks.File (4.1.0)
My appsettings.json:
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Warning",
"System": "Warning"
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "C:\\DEV\\Logs\\mylog.txt",
"rollingInterval": "Day"
}
}
]
}
},
"AllowedHosts": "*"
}
My Program.cs
public static void Main(string[] args)
{
Serilog.Debugging.SelfLog.Enable(Console.Out);
//Read Configuration from appSettings
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
//Initialize Logger
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(config)
.CreateLogger();
try
{
CreateHostBuilder(args).Build().Run();
Log.Information("Application started!");
}
catch (Exception e)
{
Log.Fatal(e, "Application failed to start.");
}
finally
{
Log.CloseAndFlush();
}
}
My controller
public void Post(SampleRequest request)
{
Log.Information("Received request {#request}", request);
}
Not even the Selflog is writing anything to Visual Studio output console Serilog.Debugging.SelfLog.Enable(Console.Out);
Try and enable SelfLog which should help you pinpoint what is going wrong. This call is slightly different to yours.
Add this in Program.cs just after you call .CreateLogger();
Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));
More details - https://github.com/serilog/serilog/wiki/Debugging-and-Diagnostics
I have Serilog logging to a rolling file in a .Net Core 3.1 app.
These are my nuget references:
<PackageReference Include="Serilog" Version="2.9.0" />
<PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.1-dev-00771" />
Also, just noticed you don't seem to have a Using section in your appsettings.json:
"Serilog": {
"Using": [ "Serilog.Sinks.RollingFile" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "RollingFile",
"Args": {
"pathFormat": "C:\\Logs\\ScreenPop\\Log-{Date}.txt"
}
}
]
},
I figured out what was the problem. I copied settings from some blog and the "WriteTo" element was actually nested inside the "MinimumLevel" one.
The correct settings would be:
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "C:\\DEV\\Logs\\mylog-.txt",
"rollingInterval": "Day"
}
}
]
},
"AllowedHosts": "*"
}

docker asp.net log configuration to enable log error too

the application uses Microsoft.Extensions.Logging
_logger.LogError
_logger.LogInformation
this is configured in appsettings.json
"Logging": {
"IncludeScopes": false,
"Console": {
"LogLevel": {
"Default": "Information"
}
}
},
then I am using mountebank as config server.
at imposter file
"propertySources": [
{
"source": {
"Logging.Console.LogLevel.Default": "Information",
}
How do I enable all log to include error as well?

Serliog Sinks: Reading from json configuration not working

The system is not autocreating logs table and logging errors in my postgres database. I am using Serilog.Sinks.PostgresSQL. What am I missing?
Program.cs:
public class Program
{
public static void Main(string[] args)
{
var path = Directory.GetCurrentDirectory();
var environmentName =Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";
var configuration = new ConfigurationBuilder()
.SetBasePath(path)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.ReadFrom.Configuration(configuration)
.CreateLogger();
try
{
var iWebHost = CreateWebHostBuilder(args).Build();
iWebHost.Run();
}
finally
{
Log.CloseAndFlush();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog();
}
appsettings.Development.json
"Serilog": {
"Using": [ "Serilog.Sinks.PostgreSQL" ],
"MinimumLevel": "Warning",
"WriteTo": [
{
"Name": "PostgreSQL",
"Args": {
"connectionString": "Server=localhost;Port=5432;Database=postgres;User Id=postgres;Password=<password>;Pooling=true;Minimum Pool Size=1;Maximum Pool Size=100;",
"tableName": "Logs",
"autoCreateSqlTable": true,
"batchPostingLimit": 1
}
}
]
}
Your problem seems that the parameter name of the auto-generated table is incorrect. Try to change the parameter like below :
"Serilog": {
"Using": [ "Serilog.Sinks.PostgreSQL" ],
"MinimumLevel": "Warning",
"WriteTo": [
{
"Name": "PostgreSQL",
"Args": {
"connectionString": "Server=localhost;Port=5432;Database=postgres;User Id=postgres;Password=<password>;Pooling=true;Minimum Pool Size=1;Maximum Pool Size=100;",
"tableName": "Logs",
"needAutoCreateTable": true,
"batchPostingLimit": 1
}
}
]
}
Reference :https://github.com/b00ted/serilog-sinks-postgresql
Updated :
You could add Serilog.Debugging.SelfLog.Enable in the Configure method to get the exceptions generated by Serilog itself , refer to below code :
Serilog.Debugging.SelfLog.Enable(msg =>
{
Debug.Print(msg);
Debugger.Break();
});
Here is the my working demo ,if you still have the error ,you could check the difference with yours .
Try it like this:
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(hostingContext.Configuration))
.Build();
I was looking for this too and found out on the project's github issue page
You need to use the "removeStandardColumns" property inside "columnOptionsSection".
WriteTo": [
{
"Name": "PostgreSQL",
"Args": {
"connectionString": "User ID=;Password=;Host=localhost;Port=5432;Database=",
"needAutoCreateTable": "true",
"schemaName": "banklink",
"tableName": "Logs",
"columnOptionsSection": {
"removeStandardColumns": [
"Message",
"Message_Tempate",
"Level",
"Timestamp",
"Exception",
"Log_Event"
],
"customColumns": [
{
"ColumnName": "message",
"DataType": "text",
"AllowNull": true
},
{
"ColumnName": "message_template",
"DataType": "text",
"AllowNull": true
},
{
"ColumnName": "logcode",
"DataType": "integer",
"AllowNull": true
},
{
"ColumnName": "level",
"DataType": "integer",
"AllowNull": true
},
{
"ColumnName": "timestamp",
"DataType": "timestamp",
"AllowNull": true
},
}
}
}
}

Resources