使用NLOG插入Guid

时间:2011-08-03 22:46:18

标签: guid nlog

我收到错误

Exception occurred in NLog ---> System.Data.SqlClient.SqlException: Conversion failed when converting from a character string to uniqueidentifier.

当我尝试在可以使用NULLS的表的UserId列中插入NULL时。

<?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"
      throwExceptions="true" internalLogFile="C:\Development\Projects\Pearson\ARIES\Development\Websites\ARIES.Web\NLog.log" internalLogLevel="Debug" >

    <!-- make sure to set 'Copy To Output Directory' option for this file -->
    <!-- go to http://nlog-project.org/wiki/Configuration_file for more information -->

    <targets>
        <target xsi:type="AsyncWrapper" queueLimit="2000" overflowAction="Grow" name="AsyncWrapperLogger" batchSize="1000">
            <target xsi:type="Database"
                    name="Database"
                    connectionStringName="ApplicationServices">
                <commandText>
                    insert into Logs(UserId, Level, Message, Exception, StackTrace, DateCreated) values(CASE WHEN @UserId IS NOT NULL AND @UserId = CAST('00000000-0000-0000-0000-000000000000' AS uniqueidentifier) THEN @UserId ELSE @UserId END, @Level, @Message, @Exception, @StackTrace, @DateCreated);
                </commandText>
                <parameter name="@UserId" layout="${event-context:item=${guid:format=UserId}}"/>
                <parameter name="@Level" layout="${level}"/>
                <parameter name="@Message" layout="${message}"/>
                <parameter name="@Exception" layout="${exception}"/>
                <parameter name="@StackTrace" layout="${stacktrace}"/>
                <parameter name="@DateCreated" layout="${date}"/>
            </target>
        </target>
    </targets>

    <rules>
        <logger name="*" writeTo="Database"/>
    </rules>
</nlog>

public static void Write(string message, Exception ex)
        {
            var logEventInfo = new LogEventInfo(NLog.LogLevel.Error, "", message);

            if (HttpContext.Current != null)
            {
                logEventInfo.Properties.Add("UserId", Guid.NewGuid());
            }

            logEventInfo.Exception = ex;

            logger.Log(logEventInfo);
        }

1 个答案:

答案 0 :(得分:2)

使用SQL Profiler修复它。它正在为空GUID发送一个空字符串。

insert into Logs(UserId, Level, Message, Exception, StackTrace, DateCreated) values(CASE WHEN @UserId = '' THEN NULL ELSE convert(uniqueidentifier, @UserId) END, @Level, @Message, @Exception, @StackTrace, @DateCreated);