NLog 将 GUID 写入数据库

NLog Writing a GUID to database

每次在数据库中写入日志时,我都无法插入 guid Id。它抛出这些错误:

Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.SqlClient.dll
Exception thrown: 'System.Data.SqlClient.SqlException' in NLog.dll

我目前拥有的:

    @"INSERT INTO [dbo].[Nlogs] 
            (Id,Message) 
            values
            (@Id,@Message)";

    databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Id", Guid.NewGuid().ToString()));
    databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Message", "${message}"));

谢谢。

How would I get it to create a new Guid for each entry?

使用${guid} or event properties

例如:

<target name="db"
        xsi:type="Database"
        connectionStringName="NLogConn"
        commandText="NSERT INTO [dbo].[Nlogs] 
            (Id,Message) 
            values
            (@Id,@Message)" >
  <parameter name="@Id"      layout="${guid}" dbType="Guid" />
  <parameter name="@Message" layout="${message}" />
</target>

更新:向上面的示例添加了 dbType 属性,这将解决任何转换问题!为此,您需要 NLog 4.6+。

来自docs

dbType - One of the values of DbType (e.g. "Int32", "Decimal", "DateTime"), or a value of DBType like prefixed with the property name, e.g. "SqlDbType.NChar" will set the property "SqlDbType" on "NChar". Another example: "NpgsqlDbType.Json" with NpgsqlParameter. Introduced in NLog 4.6

最后这样做了:

@"INSERT INTO [dbo].[Nlogs] 
        (Id,Message) 
        values
        (NewID(),@Message)";

databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Message", "${message}"));