NLog,Npgsql.PostgresException:'42804:列“DateTime”的类型为没有时区的时间戳,但表达式的类型为文本

Dim*_*try 3 nlog postgresql-9.6

我使用 NLog 登录 PostrgeSQL 数据库。

我创建了表:

CREATE TABLE "Data"."Logs"
(
    "ID" serial primary key,
    "Level" character varying(20),
    "DateTime" timestamp,
    "Message" character varying,
    "Exception" character varying
)
Run Code Online (Sandbox Code Playgroud)

然后我配置了目标:

var logDB = new DatabaseTarget()
{
    Name = "logDB",
    DBProvider = "Npgsql.NpgsqlConnection,Npgsql",
    ConnectionString = connectionString,
    KeepConnection = true,
    CommandText = $@"INSERT INTO ""{SchemaName}"".""{FileManagerLogsTableName}""(""{Level}"", ""{DateTime}"", ""{Message}"", ""{Exception}"") VALUES (@level, @datetime, @message, @exception)"
};

logDB.Parameters.Add(new DatabaseParameterInfo("@level", "${level}"));
logDB.Parameters.Add(new DatabaseParameterInfo("@datetime", "${date:format=yyyy-MM-dd hh:mm:ss}"));
logDB.Parameters.Add(new DatabaseParameterInfo("@message", "${message}"));
logDB.Parameters.Add(new DatabaseParameterInfo("@exception", "${exception:format=shortType,message :separator= - }${newline}${exception:format=method}${newline}${exception:format=stackTrace:maxInnerExceptionLevel=5:innerFormat=shortType,message,method}"));

config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Info, logDB));
LogManager.Configuration = config;
LogManager.ThrowExceptions = Debugger.IsAttached;
Run Code Online (Sandbox Code Playgroud)

但是当我想记录时:

logger.Error(ex, ex.Message);
Run Code Online (Sandbox Code Playgroud)

它抛出一个异常:

Npgsql.PostgresException:'42804:列“DateTime”的类型为没有时区的时间戳,但表达式的类型为文本

Dim*_*try 6

这是非常简单的解决方案。只需将 DateTime 转换为 CommandText 中的时间戳:

CommandText = $@"INSERT INTO ""{SchemaName}"".""{FileManagerLogsTableName}""(""{Level}"", ""{DateTime}"", ""{Message}"", ""{Exception}"") VALUES (@level, CAST(@datetime AS timestamp), @message, @exception)"
Run Code Online (Sandbox Code Playgroud)