写入数据库时出现 NLog 异常
本文关键字:NLog 异常 数据库 | 更新日期: 2023-09-27 18:31:17
我使用以下配置将NLog 4.2.3配置为写入数据库和文本文件:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" internalLogLevel="Error" internalLogFile="C:/tmp/NLog.txt">
<targets>
<target name="database" xsi:type="Database" dbProvider="Npgsql.NpgsqlFactory,Npgsql,Version=2.0.12.00,Culture=neutral,PublicKeyToken=5d8b90d52f46fda7" connectionString="Server=xxx.xxx.xxx.xxx;Port=5432;User Id=userid;Password=password;Database=testdb;">
<commandText>INSERT INTO invoice_log (message, level, logger) VALUES (@msg, @level, @logger)</commandText>
<parameter name="@msg" layout="${message}" />
<parameter name="@level" layout="${level}" />
<parameter name="@logger" layout="${logger}" />
</target>
<target name="log" xsi:type="File" layout="${longdate} | ${logger} | ${level:uppercase=true}: ${message}" fileName="${basedir}/Logs.txt" keepFileOpen="false" encoding="iso-8859-2" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="database" />
<logger name="*" minlevel="Trace" writeTo="log" />
</rules>
</nlog>
我正在尝试记录一条简单的Info
消息。它正确地记录到文本文件,但数据库失败,我在 NLog 内部日志文件中收到以下错误:
Error Error when writing to database System.MissingMethodException: No parameterless constructor defined for this object.
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at NLog.Targets.DatabaseTarget.OpenConnection(String connectionString)
at NLog.Targets.DatabaseTarget.EnsureConnectionOpen(String connectionString)
at NLog.Targets.DatabaseTarget.WriteEventToDatabase(LogEventInfo logEvent)
at NLog.Targets.DatabaseTarget.Write(LogEventInfo logEvent)
我已经查看了其他类似问题的配置(NLog 没有写入数据库表,NLog 没有写入 PostgreSQL 连接),但我看不到我的缺少什么?
根据 nlog 文档,dbProvider 是在配置文件中注册的工厂的固定名称,或者是实现 IDbConnection
的类型的完全限定名称。 Npgsql.NpgsqlConnection
实现所需的接口并具有无参数构造器。 NpgsqlFactory
没有,也没有无参数构造函数(错误的原因)。