6

背景

我正在使用来自 .Net 4.0 控制台应用程序(使用 Visual Studio 2012 编写)的NLog版本 2.0.1,我认为它是最新版本。

该应用程序很简单:

namespace NLogConsoleApplication
{
    class Program
    {
        static void Main()
        {
            NLog.LogManager.GetCurrentClassLogger().Info("A testypoos");
        }
    }
}

我有以下 NLog.config 文件:

<?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"
      autoReload="true"  
      internalLogFile="C:\Users\Public\nlog.txt"
      internalLogLevel="Debug">
  <targets>    
    <target type="Database" name="tl" >
        <connectionString>data source=.\;initial catalog=NLogTest;integrated security=false;User ID=iwillnotfallforthisone;Password=goodtry</connectionString>
        <commandText>
          insert into TestLog2 ([LogDate], [LogLevel], [LogMessage]) values (@logDate, @logLevel, @logMessage);
        </commandText>
        <parameter name="@logDate" layout="${date}"/>
        <parameter name="@logLevel" layout="${level}"/>
        <parameter name="@logMessage" layout="${message}"/>
    </target>
  </targets>
  <rules>    
    <logger name="*" minlevel="Trace" writeTo="tl" />
  </rules>
</nlog>

TestLog2 表是这样创建的:

CREATE TABLE [dbo].[TestLog2](
    [LogId] [bigint] IDENTITY(1,1) NOT NULL,
    [LogDate] [datetime] NOT NULL,
    [LogLevel] [nvarchar](20) NOT NULL,
    [LogMessage] [nvarchar](max) NOT NULL,
 CONSTRAINT [PK_TestLog2] PRIMARY KEY CLUSTERED 
(
    [LogId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

当我运行应用程序时,我得到了这个异常(我谷歌翻译了这个 - 希望它是可以理解的):

Unhandled Exception: NLog.NLogRuntimeException: Exception occurred in NLog --- > System.Data.SqlClient.SqlException:During the conversion of a nvarchar data type to a datetime data type, the value is out of range.
The statement has been terminated.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at NLog.Targets.DatabaseTarget.WriteEventToDatabase(LogEventInfo logEvent)
   at NLog.Targets.DatabaseTarget.Write(LogEventInfo logEvent)
   at NLog.Targets.Target.Write(AsyncLogEventInfo logEvent)
   --- End of inner exception stack trace ---
   at NLog.LoggerImpl.<>c__DisplayClass1.<Write>b__0(Exception ex)
   at NLog.Internal.SingleCallContinuation.Function(Exception exception)
   at NLog.Targets.Target.Write(AsyncLogEventInfo logEvent)
   at NLog.Targets.Target.WriteAsyncLogEvent(AsyncLogEventInfo logEvent)
   at NLog.LoggerImpl.WriteToTargetWithFilterChain(TargetWithFilterChain targetListHead, LogEventInfo logEvent, AsyncContinuation onException)
   at NLog.LoggerImpl.Write(Type loggerType, TargetWithFilterChain targets, LogEventInfo logEvent, LogFactory factory)
   at NLog.Logger.Info(String message)
   at NLogConsoleApplication.Program.Main() in c:\xxxxxxx\Program.cs:Line 7.

如果我将 LogDate 列更改为 nvarchar 它可以正常工作,但我真的不希望该列成为字符串,因为我希望能够根据日期对表进行排序和搜索。

笔记

  • 我在连接到德文版 SQL Sever 2012 的德文版 Windows Server 2008 R2 标准上运行它。
  • 如果我连接到英文 SQL Server 2012 实例,它工作正常。
  • 我检查了 nlog.txt 文件,那里似乎没有更多信息(只是相同的异常跟踪)

问题

也许它只是 NLog 中的一个错误,或者它只是一个我可以更改的配置,或者有一个聪明的解决方法,有谁知道我将如何让 NLog 将DateTime时间戳放入我的数据库中?

4

1 回答 1

7

我猜datetime来自 NLog 的格式是MM/dd/yyyy和德国 SQL Server 期望的dd/MM/yyyy。您可以使用以下命令明确指定日期格式:

<parameter name="@logDate" layout="${date:format=yyyy-MM-dd}"/>

SQL Server 应该能够解析日期并适当地插入它,而不管语言环境期望MM/dddd/MM.

一个类似的问题

NLog 文档

于 2013-06-18T08:20:03.737 回答