Serilog - Not logging to SQL - serilog

Hoping someone can provide some information on how to configure Serilog to write to MSSql in an ASP.Net Core DotNet 6 application, I have followed the configurations seen on the Web but nothing seems to work. Serilog logs okay to the console and to file but not to the database.
I have included all my configuration code below:
builder.Host.UseSerilog((ctx, lc) =>
lc.ReadFrom.Configuration(ctx.Configuration));
app.UseSerilogRequestLogging();
Appsetting.jason config:
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.sinks.File", "Serilog.Sinks.MSSqlServer" ],
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"WriteTo": [
{
"Name": "MSSqlServer",
"Args": {
"connectionString": "RevIntraConnection",
"tableName": "DBLogs",
"autoCreateSqlTable": false
}
},
{
"Name": "File",
"Args": {
"path": "./Logs/Log-.txt",
"rollingInterval": "Day"
}
},
{ "Name": "Console" }
]
},
Hopefully someone can provide some insight in how to get the correct configuration to make logging to SQL work
Regards
Peter

Related

Disable console sink in release environments?

quick question,
I run console sink for an asp.net core webapp. We use the console sink for development - but for performance i think it would be best to disable the sink in our production environment.
I'm assuming this sink pushes logs to stdout regardless of whether there are any listeners, hence turing the sink off would be better.
Please do correct me if i'm wrong.
Would i be able to turn off the sink under a specified condition/property/commandline arg etc. or would performance not be impacted at all?
Would i be able to disable the sink based on whether there are any listeners?
My config is as follows:
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"System": "Warning",
"System.Net.Http.HttpClient": "Warning",
"Hangfire": "Warning"
}
},
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"Enrich": [ "FromLogContext" ],
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {SourceContext}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "%CUROUTDIR%\\..\\Logs\\%PROCESSNAME%\\%PROCESSNAME% .txt",
"rollingInterval": "Day",
"rollOnFileSizeLimit": true,
"retainedFileCountLimit": 31,
"fileSizeLimitBytes": 5242880,
"outPutTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}"
}
}
]
}
}

Serilog configuration for microsoft still overrides logging information level logs

I have the following settings defined, but I am still getting all put/get requests logged to my api, even though these are supposed to be "Microsoft".
Can anyone share advice?
"Serilog": {
"Using": [ "Serilog.Sinks.Console" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{ "Name": "Console" },
{
"Name": "Seq",
"Args": { "serverUrl": "http://logserver:5341" }
},
{
"Name": "File",
"Args": {
"path": "c:\\temp\\events.api.txt",
"rollingInterval": "Day"
}
}
],
"Properties": {
"Application": "Events API"
}
},
Example of a log:
[13:55:10 INF] Source:[::1] Request: PUT https localhost:44320/api
{json request object} Responded with [200] in 2ms
return Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext());
});

NET 5.0 - serilog-sinks-file not creating logs

Since I updated my code to .NET 5.0 and used a newer version of serilog, I cannot get any rolling file anymore
I tried debugging serilog , it creates a debug file but nothing is in there
private static void CreateLogger()
{
// Init Serilog configuration
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.logs.json")
.Build();
Log.Logger = new Serilog.LoggerConfiguration().ReadFrom.Configuration(configuration)
.Enrich.WithProperty("Application", GetAssemblyProductName())
.CreateLogger();
var file = File.CreateText(AppDomain.CurrentDomain.BaseDirectory + #"serilog.txt");
Serilog.Debugging.SelfLog.Enable(TextWriter.Synchronized(file));
Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));
Serilog.Debugging.SelfLog.Enable(Console.Error);
}
here is my appsetings.log.json
{
"Serilog": {
"Using": [
"Serilog.Sinks.ApplicationInsights"
],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning",
"System.Net.Http.HttpClient": "Warning"
}
},
"WriteTo": [
{
"Name": "Async",
"Args": {
"configure": [
{
"Name": "File",
"Args": {
"pathFormat": "logs.txt",
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact",
"outputTemplate": "({SourceContext}) {Message}{NewLine}{Exception}",
"rollingInterval": "Day",
"fileSizeLimitBytes": 50000000,
"rollOnFileSizeLimit": true,
"retainedFileCountLimit": 15,
"buffered": true
}
},
{
"Name": "ApplicationInsights",
"Args": {
"restrictedToMinimumLevel": "Information",
"outputTemplate": "({SourceContext}) ({Application}/{MachineName}/{ThreadId}) {Message}{NewLine}{Exception}",
"telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
}
}
]
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "myapp"
}
}
}
am I missing something ?
thanks for helping me on this
Please someone correct me if this is wrong but I assumed you need to list the sinks you wanted to run in the Using section - therefore adding the File sink to your appsettings should fix this - as per below:
"Serilog": {
"Using": [
"Serilog.Sinks.ApplicationInsights","Serilog.Sinks.File"
],

asp net core docker serilog configuration

I have a dot net core 3.1 app that is configured to run in docker containers.
While I have managed to update simple appsettings config using docker -e flag, I am still confused when it comes to a bit complex configuration, for example, serilog config.
appsettings file:
{
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Host=172.18.101.65;Port=5432;Username=postgres;Password=pgadmin;Database=identityserver;"
},
"Serilog": {
"Using": [],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcesssId", "WithThreadId" ],
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "D:\\Logs\\IDSvr\\Log-.txt",
"outputTemplate": "{Timestamp:G} {Message}{NewLine:1}{Exception:1}",
"rollingInterval": "Day",
"shared": true
}
},
{
"Name": "Seq",
"Args": {
"serverUrl": "http://localhost:8081"
}
}
]
},
.
.
.
}
I could update the connection string using -e ConnectionStrings__DefaultConnection="..." flag, I am not sure how could I update the Serilog's WriteTo configuration section.
WriteTo is a complex object array. Hence, you have to specify the index you want to override. Lets say you want to override:
"Serilog": {
"WriteTo": [
{
"Name": "Console" // this value
},
...
You can select the key by -e Serilog__WriteTo__0__Name due to index 0 in the array. Then just pass it a value you want, like -e Serilog__WriteTo__0__Name=something.
To read that exact value in .NET Core Configuration, use Configuration["Serilog:WriteTo:0:Name"] in the startup pipeline.

How to configure Serilog.Exceptions.SqlServer in appsettings.json

I'm using appsettings.json to configure Serilog. I added Serilog.Exceptions, which works like a charm.
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Settings.Configuration", "Serilog.Exceptions" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": "%TEMP%\\Logs\\serilog-configuration-sample.txt",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception} {Properties:j}",
"rollingInterval": "Day"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId", "WithExceptionDetails" ]
}
But since I'm using Sql Server and EF Core, the documentation says I also have to configure Serilog.Exceptions.SqlServer and Serilog.Exceptions.EntityFrameworkCore.
According to this documentation this has to be added to the enrichter. In C# code this would be:
.Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
.WithDefaultDestructurers()
.WithDestructurers(new[] { new SqlExceptionDestructurer() }))
I can't figure out how to do that in appsettings.json. Can anyone help me with that?
This isn't possible at the moment, although the author is open for a PR if someone implements it.
See this issue, this discussion and this related question.

Resources