我使用NLog登录PostrgeSQL数据库。
我创建了表格:
CREATE TABLE "Data"."Logs"
(
"ID" serial primary key,
"Level" character varying(20),
"DateTime" timestamp,
"Message" character varying,
"Exception" character varying
)
然后我配置了目标:
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;
但是当我想记录时:
logger.Error(ex, ex.Message);
它引发了异常:
Npgsql.PostgresException:' 42804:column" DateTime"是没有时区的timestamp类型,但表达式是text
答案 0 :(得分:2)
这是一个非常简单的解决方案。只需将DateTime作为时间戳转换为CommandText:
CommandText = $@"INSERT INTO ""{SchemaName}"".""{FileManagerLogsTableName}""(""{Level}"", ""{DateTime}"", ""{Message}"", ""{Exception}"") VALUES (@level, CAST(@datetime AS timestamp), @message, @exception)"