Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set my own KeyGenerator instance in appsettings.json?

I already asked that question here but I feel like Stackoverflow might be faster. This is how I'm trying to do it in my json configuration file:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.AzureTableStorage" ],
    "WriteTo": [
      {
        "Name": "AzureTableStorage",
        "Args": {
          "storageTableName": "Logs",
          "connectionString": "*************",
          "keyGenerator": "MyApp.Serilog.AzureTableStorage.MyKeyGenerator"
        }
      }
    ],
    "MinimumLevel": "Verbose"
  }
}

This is my generator implementation:

public class MyKeyGenerator : IKeyGenerator
{
    public string GeneratePartitionKey(LogEvent logEvent)
    {
        return Environment.MachineName;
    }

    public string GenerateRowKey(LogEvent logEvent, string suffix = null)
    {
        return SUID.nextId().ToString();
    }
}

Obviously, the .ReadFrom.Configuration operation throws an InvalidCastException, since it tries to fit the string content into an IKeyGenerator parameter.

How should I set the keyGenerator parameter to ensure an instance of MyKeyGenerator class is created and given to that parameter?

like image 395
formixian Avatar asked Sep 06 '17 18:09

formixian


1 Answers

I cloned serilog-settings-configuration and after digging into the code, I found how they expect the JSON setting value when the actual parameter is an interface (See StringArgumentValue.cs, line 57 to 74).

The correct way to reference the type you want to pass as parameter is to give the full class and assembly names separated by a comma. That class must have a public default constructor as well.

Ex:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.AzureTableStorage" ],
    "WriteTo": [
      {
        "Name": "AzureTableStorage",
        "Args": {
          "storageTableName": "Logs",
          "connectionString": "*************",
          "keyGenerator": "MyApp.Serilog.AzureTableStorage.MyKeyGenerator, MyApp"
        }
      }
    ],
    "MinimumLevel": "Verbose"
  }
}

That way, the configurator can instanciate the class properly!

like image 180
formixian Avatar answered Nov 02 '22 12:11

formixian