question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Problem switching configuration from code to appsettings.json

See original GitHub issue

In my project I’m trying to switch from the Fluent configuration in code to an appsettings.json one. Here there is my C# Fluent configuration

ColumnOptions columnOptions = new ColumnOptions();
columnOptions.Store.Remove(StandardColumn.Properties);
columnOptions.Store.Add(StandardColumn.LogEvent);
columnOptions.Level.StoreAsEnum = true;

LoggingLevelSwitch levelSwitch = new LoggingLevelSwitch();
	levelSwitch.MinimumLevel = LogEventLevel.Debug;
				
Log.Logger = new LoggerConfiguration()
	.MinimumLevel.ControlledBy(levelSwitch)
	.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
	.Enrich.WithMachineName()
	.Enrich.WithProperty("Application", "My App")
	.Enrich.WithProperty("Environment", Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"))
	.Enrich.WithThreadId()
	.Enrich.With<EventTypeEnricher>()
	.Enrich.FromLogContext()
	.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss.fff} {ThreadId} {EventType:x8} {Level:u3}] {Message:lj}{NewLine}{Exception}")
	.WriteTo.MSSqlServer(configuration.GetConnectionString("LogConnectionString"), "Logs", columnOptions: columnOptions, autoCreateSqlTable: true)
	.CreateLogger();

And this is my actual appsettings.json

{
  "ConnectionStrings": {
    "DbContext": "Server=..."
  },
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.MSSqlServer", "MyProject.AssemblyName" ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId", "EventTypeEnricher" ],
    "Properties": {
      "Application": "My App",
      "Environment": "Development"
    },
    "LevelSwitches": { "$levelSwitch": "Debug" },
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "[{Timestamp:HH:mm:ss.fff} {ThreadId} {EventType:x8} {Level:u3}] {Message:lj}{NewLine}{Exception}"
        }
      },
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "Server=...",
          "tableName": "Logs",
          "columnOptionsSection": {
            "addStandardColumns": [ "LogEvent" ],
            "removeStandardColumns": [ "Properties" ],
            "level": {
              "columnName": "Level",
              "storeAsEnum": true
            }
          },
          "autoCreateSqlTable": true
        }
      }
    ]
  }
}

Now I’m currently dealing with some problems:

  1. My custom Enricher EventTypeEnricher, defined inside the MyProject.AssemblyName that I added to Using, is not loaded. I can see because of the Console output template shows a blank space instead of the numeric values.

  2. Adding the MSSqlServer block leads to the following Exception:

    Exception has been thrown by the target of an invocation. {System.Data.DuplicateNameException: A column named ‘Level’ already belongs to this DataTable.}

  3. I’m not sure about configuration of LevelSwitches

  4. Is it possible to configure the Properties.Environment value dynamically, like it is in my code?

The in code configuration is fully functional. My actual versions of Serilog packages are:

  • Serilog.AspNetCore v2.1.1
  • Serilog.Sinks.Console v3.1.1
  • Serilog.Sinks.MSSqlServer v5.1.3-dev-00202
  • Serilog.Settings.Configuration v3.0.0-dev-00119
  • Serilog.Enrichers.Environment v2.1.2

Thanks!

UPDATE

About problem with MSSqlServer configuration, if I remove the

"level": {
  "columnName": "Level",
  "storeAsEnum": true
}

block, I’ve no more Exceptions, but that leads (obviously) to a runtime Exception:

Unable to write 2 log events to the database due to following error: The given value of type String from the data source cannot be converted to type tinyint of the specified target column.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:6 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
OculiViridicommented, Aug 27, 2018

@MV10 And so, I’m set now! 👍 My JSON configuration is actually working.

About the EventTypeEnricher, I found that I was missing the appropriate extension method:

public static LoggerConfiguration WithEventType(this LoggerEnrichmentConfiguration enrichmentConfiguration)
{
	if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
	return enrichmentConfiguration.With<EventTypeEnricher>();
}

and the correct configuration on JSON file:

"Serilog": {
    "Using": [ "MyApp.Assembly.Name" ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId", **"WithEventType"** ],
}

Thank you very much!

1reaction
MV10commented, Aug 27, 2018

Glad to help.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Changes to appsettings.json config files not picked up?
I recently noticed some strange behaviour in Visual Studio. If I edit my appsettings.json file then run in debug F5 , the changed...
Read more >
Does a change on appsettings.json require IIS restart?
The application must restart to load appsettings.json. Restarting IIS will work or restarting the specific application in IIS will work too.
Read more >
Appsettings.json in .NET: How to read and get a value
NET with our online courses 0:34 Problem with AppSettings in web. config 1:17 AppSettings. json in ASP.NET Core 1:44 Use configuration in ...
Read more >
Intro to AppSettings in .NET Core - YouTube
AppSettings are a big deal in .NET Core. If you are just using appsettings. json, you are really missing out. There is so...
Read more >
Appsettings.json environment: Setup files and use ... - YouTube
Separate appsettings. json files can be set up for different environments in .NET and .NET Core projects. An ASP.NET Core C# application ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found