带有 .NET Core 的 NLog/SQLite

NLog/ SQLite with .NET Core

我正在尝试从 .NET Core 2.1 Web 应用程序项目中的 NLog 登录到 SQLite 数据库。

我有这样的配置:

<?xml version="1.0" encoding="utf-8"?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xsi:schemaLocation="NLog NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      throwExceptions="true"
      internalLogIncludeTimestamp="true"
      internalLogFile="nlog-internal.log"
      internalLogLevel="Error">
    <targets>
        <target xsi:type="Database"
                name="database"
                commandType="Text"
                dbProvider="Microsoft.Data.Sqlite.SqliteConnection, Microsoft.Data.Sqlite"
                connectionString="${var:appDbConnectionString}"
                commandText="Layout">
            <commandText>
                insert into Logs (TimestampUtc, Application, Level, Message, Exception, Logger)
                values (@timestamputc, @application, @level, @message, @exception, @logger);
            </commandText>
            <parameter name="@timestamputc" layout="${date:universalTime=true:format=yyyy-MM-dd HH\:mm\:ss.fff}" />
            <parameter name="@application" layout="My App" />
            <parameter name="@level" layout="${level}" />
            <parameter name="@message" layout="${message}" />
            <parameter name="@exception" layout="${exception:format=tostring}" />
            <parameter name="@logger" layout="${logger}" />
        </target>
    </targets>
    <rules>
        <logger name="MyApp.*" minlevel="Info" writeTo="database" />
        <logger name="*" minlevel="Warn" writeTo="database" />
    </rules>
</nlog>

...我的 SQLite table 是这样设置的:

CREATE TABLE "Logs" ( 
    `Id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 
    `TimestampUtc` TEXT NOT NULL, 
    `Application` TEXT NOT NULL, 
    `Level` TEXT NOT NULL, 
    `Message` TEXT NOT NULL, 
    `Logger` TEXT NOT NULL, 
    `Exception` TEXT )

...但是当我尝试记录某些内容时,出现以下异常:

System.AggregateException
  HResult=0x80131500
  Message=An error occurred while writing to logger(s).
  Source=Microsoft.Extensions.Logging
  StackTrace:
   at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
   at Microsoft.Extensions.Logging.LoggerExtensions.Log(ILogger logger, LogLevel logLevel, EventId eventId, Exception exception, String message, Object[] args)
   at Microsoft.Extensions.Logging.LoggerExtensions.LogError(ILogger logger, String message, Object[] args)
   at Microsoft.AspNetCore.NodeServices.HostingModels.OutOfProcessNodeInstance.OnErrorDataReceived(String errorData)
   at Microsoft.AspNetCore.NodeServices.HostingModels.OutOfProcessNodeInstance.<>c__DisplayClass24_0.<ConnectToInputOutputStreams>b__1(Object sender, DataReceivedEventArgs evt)
   at System.Diagnostics.Process.ErrorReadNotifyUser(String data)
   at System.Diagnostics.AsyncStreamReader.FlushMessageQueue(Boolean rethrowInNewThread)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Diagnostics.AsyncStreamReader.<>c.<FlushMessageQueue>b__17_0(Object edi)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()

Inner Exception 1:
SqliteException: SQLite Error 19: 'NOT NULL constraint failed: Logs.TimestampUtc'.

该消息似乎表明我正在尝试将空值插入 TimestampUtc 字段,但事实并非如此;根据我读过的所有文档,时间戳参数的布局字符串看起来是正确的,不应生成空值。

我的格式字符串有误吗?我的参数语法错误吗?我是否需要对我的查询做一些我没有想到的事情才能让它工作?

作为替代方案,您可以使用 System.Data.SQLite (NuGet) 代替。

nlog.config 片段:

<target xsi:type="Database"
            name="db"
            dbProvider="System.Data.SQLite.SQLiteConnection, System.Data.SQLite"
            connectionString="Data Source=database.db;">
   ...
</target>