当将NLog与ASP.NET Core和SQLite一起使用时,参数为空(或未提供给CommandText)

Parameters empty (or not supplied to CommandText) when using NLog with ASP.NET Core and SQLite

我已经使用文档中的示例在ASP.NET Core MVC应用程序中设置了NLog。 登录到文件(target = file)可以正常进行。

但是,登录到Sqlite数据库会导致异常:

2018-10-30 20:04:41.4394 Error DatabaseTarget(Name=db): Error when
writing to database. Exception: System.InvalidOperationException: Must
add values for the following parameters: @MachineName, @Logged,
@Level, @Message, @Logger, @Callsite, @Exception at
Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior
behavior) at Microsoft.Data.Sqlite.SqliteCommand.ExecuteNonQuery()
at NLog.Targets.DatabaseTarget.WriteEventToDatabase(LogEventInfo
logEvent) at NLog.Targets.DatabaseTarget.Write(LogEventInfo
logEvent)

有什么想法为什么这些参数的值是空的? 还是根本不传递参数?

NLog配置文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?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">

  <targets>
    <target xsi:type="File" name="file" fileName="nlog-${shortdate}.log"
            layout="${longdate}|${machinename}|${level:upperCase=true}|${logger}|${callsite}|${message} ${exception:tostring}" />

    <target xsi:type="Database"
            name="db"
            dbProvider="Microsoft.Data.Sqlite.SqliteConnection, Microsoft.Data.Sqlite"
            connectionString="Data Source=database.db;">

      <commandText>
        INSERT INTO Log (MachineName, Logged, Level, Message, Logger, CallSite, Exception)
        VALUES (@MachineName, @Logged, @Level, @Message, @Logger, @Callsite, @Exception);
      </commandText>

      <parameter name="@MachineName" layout="${machinename}" />
      <parameter name="@Logged" layout="${longdate}" />
      <parameter name="@Level" layout="${level:upperCase=true}" />
      <parameter name="@Message" layout="${message}" />
      <parameter name="@Logger" layout="${logger}" />
      <parameter name="@CallSite" layout="${callsite}" />
      <parameter name="@Exception" layout="${exception:tostring}" />
    </target>
  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="file" />
    <logger name="*" minlevel="Info" writeTo="db" />
  </rules>
</nlog>


无法使用Microsoft.Data.Sqlite解决此问题,我改用System.Data.SQLite(NuGet),它立即解决了该问题。

删除Microsoft.Data.Sqlite引用,然后在.csproj文件中添加引用System.Data.SQLite(在编写时为1.0.109.2)。 将nlog.config中的dbProvider属性值更新为System.Data.SQLite.SQLiteConnection, System.Data.SQLite即可。

nlog.config片段:

1
2
3
4
5
6
<target xsi:type="Database"
            name="db"
            dbProvider="System.Data.SQLite.SQLiteConnection, System.Data.SQLite"
            connectionString="Data Source=database.db;">
   ...
</target>