Search code examples
.net-coreserilog

Serilog Named Connection String


I am trying to configure Serilog on .Net core to write to a SQL table using a named connection string. I can get everything to work if I put the connection string directly in the "Serilog" section of the appsettings file. But I want it to use the same connection string as Entity Framework so I don't want to define it twice. Plus the recommendation seems to be to not store this information directly in the appsettings file for security reasons.

Here is the relevant portion of the settings file:

{
    "Name": "MSSqlServer",
    "Args": {
        "connectionString": "Development",
        "schemaName": "app",
        "tableName": "Logs",
        "restrictedToMinimumLevel": "Information"
    }
}

The Development connection string is defined in my "user secrets" in Visual Studio.

{
    "ConnectionStrings": {
        "Development": "Server=...",
        "Staging": "Server=...",
        "Production": "Server=..."
    }
}

As I mentioned, if I replace "Development" with the actual string it works. I should also add that Entity Framework is using the Development connection string so I am pretty certain the string itself is good.

I am loading the configuration in the Startup.Configure method this way

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(_configuration)
    .CreateLogger();

Oddly, if I manually add the MSSqlServer object in this same method it will work (after removing the MSSqlServer section of the appsetting file). Obviously this isn't ideal since changing any of the properties will require a recompile of the app

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(_configuration)
    .WriteTo.MSSqlServer(
        connectionString: _configuration.GetConnectionString(env.EnvironmentName),
        schemaName: "app",
        tableName: "Logs",
        restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information
    )
   .CreateLogger();

I have found this thread on GitHub that tells me this may be a known issue. Unfortunately there seems to be very little activity on it if this is true.

I am using Serilog.AspNetCore version 2.1.1, Serilog.Settings.Configuration version 3.0.1, Serilog.Sinks.MSSqlServer version 5.1.2 and .Net core version 2.1.

Any help would be greatly appreciated.


Solution

  • I was having the same problem. Installing the latest dev packages solved it for me:

    Install-Package Serilog.Settings.Configuration -version 3.0.2-dev-00187 
    Install-Package Serilog.Sinks.MSSqlServer -version 5.1.3-dev-00232