Home > front end >  Nlog with Npgsql throws NLog.NLogConfigurationException: 'DatabaseParameterInfo' cannot as
Nlog with Npgsql throws NLog.NLogConfigurationException: 'DatabaseParameterInfo' cannot as

Time:12-23

my code is throwing me expcetion Unhandled exception. NLog.NLogConfigurationException: 'DatabaseParameterInfo' cannot assign unknown property 'parameterName'='@Exception'

I'm using NLog package (5.1.0) in my ASP.NET WEB API project. My database is PostgreSQL so I use Npgsql (Npgsql.EntityFrameworkCore.PostgreSQL and transitive package Npgsql). My configuration in appsettings.json looks like

...
"NLog": {
    "throwConfigExceptions": true,
    "autoReload": true,
    "extensions": [
      { "assembly": "NLog.Extensions.Logging" },
      { "assembly": "NLog.Web.AspNetCore" }
    ],
    "targets": {
      "async": true,
      "console": {
        "type": "Console"
      },
      "database": {
        "type": "Database",
        "dbProvider": "Npgsql.NpgsqlConnection, Npgsql",
        "connectionString": "",
        "commandText": "INSERT INTO Logs (Exception) VALUES (@Exception)",
        "parameters": [
          {
            "parameterName": "@Exception",
            "layout": "${exception:tostring}"
          }
        ]
      }
    },
    "rules": [
      {
        "logger": "*",
        "minLevel": "Trace",
        "writeTo": "console"
      },
      {
        "logger": "*",
        "minLevel": "Error",
        "writeTo": "database"
      }
    ]
  },
...

I don't set the connection string in the application settings because I want to do it programmatically in program.cs. my program.cs looks like

...
    var builder = WebApplication.CreateBuilder(args);
    var configuration = builder.configuration;

    var dbConnectionOptions = new DbConnectionOptions(configuration);
    configuration.GetSection("NLog")
        .GetSection("targets")
        .GetSection("database")
        .GetSection("connectionString").Value = dbConnectionOptions.AppDb.ConnectionString;
...

In Npgsql specification https://www.npgsql.org/doc/basic-usage.html#parameters I see, that there are two ways of defining parameters. One is using $ and another is using @ but nothing seems to work. Does anyone know what can I change to fix it?

I've tried setting commandText Values as @Exception, $Exception, Exception, %Exception, and setting parameterName as @Exception, $Exception, Exception, %Exception (mixing all options), but always got same result.

CodePudding user response:

NLog complains about not recognizing the property parameterName.

Try replacing:

"parameterName": "@Exception",

With:

"name": "@Exception",

See also: https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-configuration-with-appsettings.json

Also notice that NLog v5 requires NLog.Database-nuget-package for the NLog DatabaseTarget to work.

  • Related