I am getting the error
Exception occurred in NLog ---> System.Data.SqlClient.SqlException: Conversion failed when converting from a character string to uniqueidentifier.
when I try to insert a NULL in the UserId column of the table which can take NULLS.
<?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);
}
Fixed it by using SQL Profiler. It was sending an empty string for the null 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);
精彩评论